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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With