Add items to List While Iterating - Python
Last Updated :
27 Nov, 2024
Improve
Python has many ways to append to a list while iterating. List comprehension is a compact and efficient way to append elements while iterating. We can use it to build a new list from an existing one or generate new values based on a condition.
a = [1, 2, 3]
a += [i + 4 for i in range(3)]
print(a)
Output
[1, 2, 3, 4, 5, 6]
Other ways to append to a list while iterating are:
Table of Content
Using extend() Method
If we want to append multiple items to a list at once, we can use the extend() method. This method adds all elements from another list to the original list.
a = [1, 2, 3]
a.extend([4, 5, 6])
print(a)
Output
[1, 2, 3, 4, 5, 6]
Using a While Loop
Sometimes, a while loop might be useful for appending to a list. You can manually control the loop’s conditions.
a = [1, 2, 3]
i = 0
while i < 3:
a.append(i + 4)
i += 1
print(a)
Output
[1, 2, 3, 4, 5, 6]
Using map() Function
The map() function applies a function to all items in an iterable. This method can also be used to append items while iterating.
a = [1, 2, 3]
a += list(map(lambda x: x + 4, range(3)))
print(a)
Output
[1, 2, 3, 4, 5, 6]