Skip to content

Python append to list while iterating | Example code

  • by

Use the Python List append() method to append elements to a list while iterating over the list using a for-in loop. If you append a new element to the list while iterating the list results in a list containing the original list’s elements and the new elements.

Python Example Adding an element to list while iterating

Python simple example code.

Get the length of the list obj and iterate over the list. Then call list.append(object) within the loop to add the object to the list while iterating over the list.

a_list = ["a", "b", "c"]

list_length = len(a_list)

for i in range(list_length):
    a_list.append("New " + i.__str__())

print(a_list)

Output:

Python append to list while iterating

Read more examples in this topic: Python add to list in a loop

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *