How to modify list entries during for loop?

python modify list while iterating
python modify list element while iterating
python for loop change value
python enumerate
python append to list while iterating
list comprehension python
python list
python list methods

Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification?

It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

Can't modify list elements in a loop Python, for idx, item in enumerate(li): li[idx] = 'foo' In fact with list comprehension you are not modifying the list, you are creating a new list and then� If you want to modify your list you can do it with enumerate: >>> li = ["spam", "eggs"] >>> for i,_ in enumerate(li): li[i] = "foo" >>> li ['foo', 'foo'] or with xrange (in Python 2.7, use range in python 3): >>> for i in xrange(len(li)): li[i] = "foo" >>> li ['foo', 'foo']

Since the loop below only modifies elements already seen, it would be considered acceptable:

a = ['a',' b', 'c ', ' d ']

for i, s in enumerate(a):
    a[i] = s.strip()

print(a) # -> ['a', 'b', 'c', 'd']

Which is different from:

a[:] = [s.strip() for s in a]

in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.

Caution: Although you can modify entries this way, you can't change the number of items in the list without risking the chance of encountering problems.

Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:

b = ['a', ' b', 'c ', ' d ']

for i, s in enumerate(b):
    if s.strip() != b[i]:  # leading or trailing whitespace?
        del b[i]

print(b)  # -> ['a', 'c ']  # WRONG!

(The result is wrong because it didn't delete all the items it should have.)

Update

Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):

b = ['a',' b', 'c ', ' d ']

b[:] = [entry for entry in b if entry.strip() == entry]

print(b)  # -> ['a']  # CORRECT

Why can't you modify lists through 'for in' loops in Python?, It isn't the element itself. So, if you loop the first way and try “item = 7”, it will not change that element of the list to 7� Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

Modifying a list while looping through it in Python, Here is an interesting thing that I found. x is a SymPy Symbol: I would have expected to get a = [], but it only removes the first item. And yes, x +� If you want to change the list, you’ll need to use a while-loop. Because for-loops are simpler and easier to read, you should use a for-loop in your code wherever the goal is to refer to the items of a list, but without changing the list. If you want to change which items the list contains, you should use a while-loop. Using range to create a list of int values. Some functions return lists.

Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.

You can use list comprehension:

l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]

or just do the C-style for loop:

for index, item in enumerate(l):
    l[index] = item.strip()

Removing items from a list while iterating over the list, In the loop body, the 1 is removed from the list, making 2 the first element in the list. The iterator still points to the first element (now 2 ). For the second iteration, the� How to Make List<T>.ForEach Modify the List by Larry Spencer Tuesday, July 24, 2012 3:34 PM Here's a gotcha that's obvious once you see it, but was the cause of a bug that lived for several months undetected in code I came across today.

No you wouldn't alter the "content" of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.

If you had a list of objects you knew were mutable, you could do this as long as you don't change the actual contents of the list.

Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.

An Introduction to Python Lists, The list type also allows you to assign to individual items or slices, and to delete Note that operations that modify the list will modify it in place. an internal index, which is incremented for each loop iteration. Out of the other presented solutions, all but the one using Java 8 seem to be O(n**2), i.e., too slow when the list(*) gets a bit bigger. The simplest fast solution is to create an empty list and add all elements not less than three. If you need to modify the original list, then clean if afterwards and add all elements from the auxiliary list.

Thou Shalt Not Modify A List During Iteration, Merely updating or mutating the list items is fine. The author of this code snippet probably expected it to iterate over each element of the list,� If you really want to use a for-in loop, you can use the built-in Python function enumerate () which will return a tuple consisting of the list index and the corresponding value in each iteration. Then you can use the index to modify your list. 12.3K views View 13 Upvoters

Python: Editing list while iterating over it, How to modify list entries during for loop?, Modifying each element while iterating a list is fine, as long as you do not change add/remove elements But in Python� extend (): Adds items from an existing list and into the current list. insert (): Adds a new entry to the position specified in the list. pop (): Removes an entry from the end of the list. remove (): Removes an entry from the specified position in the list.

Doing Something with Every Element in a List, foreach $var (sort keys %ENV) { print "$var=$ENV{$var}\n"; } The variable set to each value in the list is called a loop variable or iterator variable. This aliasing means that using a foreach loop to modify list values is both more readable and� // ListIterator - traverse a list of elements in either forward or backward order // An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, // and obtain the iterator's current position in the list. System.out.println(" ==============> 4.

Comments
  • A string does not a mutable value make.
  • @user470379: Whether the elements of the list are mutable isn't relevant to whether it's safe or not to modify the list they're in while looping though it.
  • The slice assignment is clever and avoids modifying the original during the loop, but requires the creation of a temporary list the length of the original.
  • why do we assign b = a?
  • @Vigrond: So when the print b statement is executed, you can tell if a was modified in-place rather than replaced. Another possibility would have been a print b is a to see if they both still refer to the same object.
  • why a[:] = and not just a = ?
  • @kdubs: "...with slice assignment if you need to retain existing references to the list."
  • Why does Python only make a copy of the individual element in the syntax for i in a though? This is very counterintuitive, seemingly different from other languages and has resulted in errors in my code that I had to debug for a long period of time. Python Tutorial doesn't even mention it. Though there must be some reason to it?
  • @JIXiang: It doesn't make a copies. It just assigns the loop variable name to successive elements or value of the thing being iterated-upon.
  • Eww, why use two names (a[i] and s) for the same object in the same line when you don't have to? I'd much rather do a[i] = a[i].strip().
  • @Navin: Because a[i] = s.strip() only does one indexing operation.