Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of currently iterated element in list

Tags:

python

problem: when you use construction

for a in _list_:     print a 

it prints every item in array. But you can't alter array. Is it possible to alter value of array (something like a=123, but that ain't working) I know it's possible (for example in while loop), but I want to do it this way (more elegant)

In PHP it would be like

foreach ($array as &$value) {     $value = 123; } 

(because of & sign, is passed as reference)

like image 955
kleofas Avatar asked Jun 30 '11 00:06

kleofas


People also ask

Can I modify list while iterating?

The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.

How do you change a value in a for loop in Python?

Python for loop change value of the currently iterated element in the list example code. Or you can use list comprehensions (or map ), unless you really want to mutate in place (just don't insert or remove items from the iterated-on list). Use a for-loop and list indexing to modify the elements of a list.

How do you change an element in an array in Python?

Changing Multiple Array Elements In Python, it is also possible to change multiple elements in an array at once. To do this, you will need to make use of the slice operator and assign the sliced values a new array to replace them.


2 Answers

for idx, a in enumerate(foo):     foo[idx] = a + 42 

Note though, that if you're doing this, you probably should look into list comprehensions (or map), unless you really want to mutate in place (just don't insert or remove items from iterated-on list).

The same loop written as a list comprehension looks like:

foo = [a + 42 for a in foo] 
like image 59
Cat Plus Plus Avatar answered Oct 04 '22 04:10

Cat Plus Plus


Because python iterators are just a "label" to a object in memory, setting it will make it just point to something else.

If the iterator is a mutable object (list, set, dict etc) you can modify it and see the result in the same object.

>>> a = [[1,2,3], [4,5,6]] >>> for i in a: ...    i.append(10) >>> a [[1, 2, 3, 10], [4, 5, 6, 10]] 

If you want to set each value to, say, 123 you can either use the list index and access it or use a list comprehension:

>>> a = [1,2,3,4,5] >>> a = [123 for i in a] >>> a [123, 123, 123, 123, 123] 

But you'll be creating another list and binding it to the same name.

like image 35
JBernardo Avatar answered Oct 04 '22 05:10

JBernardo