1

I am trying to update a list using for loop, I understand that it does not work but am unsure what is the best way to do it.

l = ['axy','axy','bxy','cxy']

for i in l:

    item = 'ax'
    l = [s for s in l if not s.startswith(item)]
    print l

Output:

['bxy', 'cxy']
['bxy', 'cxy']
['bxy', 'cxy']
['bxy', 'cxy']

Expected Output:

['bxy', 'cxy']
['bxy', 'cxy'] 
['bxy', 'cxy'] 

#1 less loop as the list should've been updated to l = ['bxy','cxy'] after the first loop

It tells me that the list gets updated but the iteration does not, is there anyway I can use list comprehension in the loop?

I am using this to remove files, so when the file is removed, I need to update the list so it does not get prompted again.

BernardL
  • 5,162
  • 7
  • 28
  • 47

2 Answers2

3

You are iterating a list with four items and upon each iteration you're printing the list - that's the first 4 prints. The last one is coming from the last line in the program: print l.

The four iterations come from the fact that the list, while entering the loop, had 4 items. That list is being iterated while inside the loop you're just overriding the pointer to the list l (the original list still exist only now, after you're re-assigned l you can't access it anymore).

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • If I use something like remove instead, will it count as overriding and still wont be accessible? – BernardL Nov 21 '16 at 04:22
  • 1
    @BernardL if you'll use `remove` you'll be modifying the list you're iterating and that might cause different kind of issues. Try to ask the question in a way that describes *what* you want to achieve and not *how* you're trying to do it. There might be other (simpler) ways to achieve your goal, like constructing a new list and adding to it only items that you're interested in. – Nir Alfasi Nov 21 '16 at 04:36
-1

This is because assignment always create a new reference and does not update list in place.

When the for loop was evaluated l was replaced by its current value. Now this does not happen every iteration of loop. It only occurs once.

Whey you changed the value of l inside the loop using '=' it created the new reference, so the name l point to a different list altogether. It does not affect the list which was already evaluate in for loop.

If you use operation which updates the list inplace like update and remove you will see the output which you are expecting

saurabh baid
  • 1,819
  • 1
  • 14
  • 26