How I can change element in array?
I have this code, but I expected that it would print [[5,5],[1,4]]
. But it wouldn't. It still prints [[1,2],[1,4]]
.
x = [[1,2], [1,4]]
for element in x:
if element[1] == 2:
element = [5,5]
print x
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
When it is required to replicate the duplicate occurrence in a string, the keys, the 'index' method and list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it.
Change a list element requires an index.
list_object[index] = new_value
Using enumerate
, you can iterate the list and get a indexes.
>>> x = [[1,2], [1,4]]
>>> for i, element in enumerate(x):
... if element[1] == 2:
... x[i] = [5,5]
...
>>> x
[[5, 5], [1, 4]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With