This tutorial will discuss about unique ways to append elements to list while iterating in Python.
Table Of Contents
Add elements to list while looping through it
Suppose we have a list of strings, and we want to add elements to this list but while looping through it. Basically, while iterating, we will check if any string from list matches a given string, then add a new string into the same list. But the catch is, if we are iterating through a list using a for loop
and in operator
, then we can not modify list contents while looping through it. It can cause undefined behaviour. Therefore, to avoid any problem, we can iterate through list by idex positions, and then we can easily add elements to list while iterating.
Let’s see the complete example,
listOfStrings = ['is', 'are', 'at', 'why', 'what'] # get number of elements in list sizeOfList = len(listOfStrings) # Iterate over all elements of list by index position for i in range(sizeOfList): # fetch element at index i elem = listOfStrings[i] # check if element matches the string if elem == "at": # add a new element to list listOfStrings.append('the') print(listOfStrings)
Output
['is', 'are', 'at', 'why', 'what', 'the']
Related Articles:
We first fetched the size of list, and then iterated through a range of numbers i.e. from 0 to N, where N is the size of list. During iteration, for each number i, we selected an element from list at ith index, converted it to string, and appended it to the list.
Frequently Asked:
- Add element to list without append() in Python
- How to add items from a list to another list in Python?
- Python List insert()
- Add element to list while iterating in Python
Add elements to list using for-loop
We can directly loop through a range of numbers, and for each number, we can add it to the list using its append() function. This way we can simply add elements to a list in a loop.
Let’s see the complete example,
listOfStrings = ['is', 'are', 'at', 'why', 'what'] # Iterate over all a range of numbers from 0 to 5 for i in range(5): # add a new element to list listOfStrings.append(str(i)) print(listOfStrings)
Output
['is', 'are', 'at', 'why', 'what', '0', '1', '2', '3', '4']
It added five elements in list using a for loop.
Summary
We learned about different ways to add elements in a list using a loop. Thanks.