Use the append() method to add elements to a list while iterating over the list. Means you can add item in the list using loop and append method.
Example how to add to list in a loop in Python
Simple python example code.
Adding the number 0 to 4
The list append function does not return any value, it just adds the value to the list.
a = []
for i in range(5):
a.append(i)
print(a)
Output:
Append elements to a list while iterating over the list
within the loop to add object
to list
while iterating over the list.
list1 = ["a", "b", "c"]
list_length = len(list1)
for i in range(list_length):
list1.append("New " + list1[i])
print(list1)
Output:
Do comment if you have any doubts and suggestions on this Python list code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
When i was facing the same problem and searching the solution, i got my soloution here. You can check this link too may be useful ( https://kodlogs.net/299/add-to-the-list-in-a-loop-using-python%5B^])