How to insert item at end of Python list

Published on Aug. 22, 2023, 12:16 p.m.

To add elements to a list in Python using a for loop, you can use the append() method. Here is an example:

my_list = []
for i in range(5):
    my_list.append(i)
print(my_list)  # Output: [0, 1, 2, 3, 4]

In this example, we first define an empty list my_list. We then use a for loop to iterate over a range of numbers from 0 to 4. On each iteration, the current number i is appended to the end of the list using the append() method. Finally, we print the resulting list, which contains all the added elements.

Note that you can change the range provided to the range() function to control the number of elements added to the list. Additionally, you can modify the append() method to add specific elements to the list in each iteration of the loop.

Tags:

related content