How to modify list entries during for loop?

前端 未结 9 955
旧巷少年郎
旧巷少年郎 2020-11-22 01:56

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 re

9条回答
  •  感动是毒
    2020-11-22 02:24

    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)
    

提交回复
热议问题