Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two ways of looping over list - difference

Tags:

python

list

I have to reverse every word in a list which length is greater that 4. So I tried:

for word in words:
    if len(word) >= 5:
        word = word[::-1]

and it didn't work. But this:

 for i in range(len(words)):
        if len(words[i]) >= 5:
            words[i] = words[i][::-1]

works fine. What's the diference?

like image 644
Igor234 Avatar asked Nov 18 '22 12:11

Igor234


1 Answers

When you iterate through a list Python creates references (with same ID) to your variable. However these are not editable in place. Check this for instance: Can't modify list elements in a loop Python

Consider this example which hopefully can help you out:

words = ['abcdef','abc']

for ind,i in enumerate(words):
    print('Loop {}'.format(ind))
    i = i[::-1]
    print('words equal {}'.format(words))
    words[ind] = words[ind][::-1] 
    print('words equal {}'.format(words))    
    print()

Returns:

Loop 0
words equal ['abcdef', 'abc']   # <--- after changing i (nothing changed)
words equal ['fedcba', 'abc']   # <--- after changing words[ind]

Loop 1
words equal ['fedcba', 'abc']   # <--- after changing i (nothing changed)
words equal ['fedcba', 'cba']   # <--- after changing words[ind]

in your case

The most simple solution would be to use a list comprehension. Consider this:

rWords = [word[::-1] if len(word) >=5 else word for word in words]
like image 158
Anton vBR Avatar answered Nov 29 '22 04:11

Anton vBR