Python add to list in a loop | Appending elements in List example code

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:

Python add to list in a loop

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:

Append elements to a list while iterating over the list

Do comment if you have any doubts and suggestions on this Python list code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.