for loop to create list in python

To create a list in Python using a for loop, you can define an empty list and then use the append() method to add items to it within the for loop. Here is an example:

main.py
my_list = []  # define an empty list
for i in range(0, 5):
    my_list.append(i)  # add the current value of i to the list
print(my_list)  # output [0, 1, 2, 3, 4]
164 chars
5 lines

In this example, the range() function is used to create a sequence of numbers from 0 to 4. The for loop then iterates through this sequence, and for each number, it appends it to the my_list list using the append() method. Finally, the list is printed to the console to show the result of the loop.

You can customize the range of the loop and the values that are appended to the list as per your requirement.

related categories

gistlibby LogSnag