How to modify list entries during for loop?

前端 未结 9 704
旧巷少年郎
旧巷少年郎 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:00

    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()
    

提交回复
热议问题