Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change element in array [duplicate]

Tags:

python

list

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
like image 261
Kenenbek Arzymatov Avatar asked Dec 15 '15 12:12

Kenenbek Arzymatov


People also ask

How do you replace duplicate values in an array?

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.

How do you replace duplicates in a string in Python?

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.


1 Answers

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]]
like image 199
falsetru Avatar answered Oct 18 '22 01:10

falsetru