//
🩹
For loops with enumerate
Search
Try Notion
Drag image to reposition
🩹
For loops with enumerate
Property
Done
3 more properties
I want to change all elements in width_lst that are equal to “1” to an empty string “”.
Before, I was using len() combined with range() to iterate over the list:
for i in range(len(width_lst)): if width_lst[i] == "1": width_lst[i] = ""
Python
A more readable alternative is to use enumerate:
for i, value in enumerate(width_lst): if value == "1": width_lst[i] = ""
Python
Enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained for that count. Example taken from the documentation:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Python
References