The Python list values are comma-separated and All the items are enclosed within the square brackets. You need to iterate over items in a list by using for loop store values in a list in Python.
.append
needs to be called on the list
Store values in a list in Python using for loop
Simple example code.
num_lists = int(input("How many lists do you want? "))
lists = []
for p in range(num_lists):
lists.append(p)
print(lists)
Output:
When you use range, you essentially create a list that Python reiterates through. Thus, for x in range(0, 100) creates a temporary list with numbers from 0 to 100.
If you wanted to take this a step further, you could use a list comprehension to avoid needing to use append
altogether, and provide a parameter to indicate how many random numbers you want:
Here’s an example of how you can use a for
loop to store values in a list:
# Initialize an empty list
my_list = []
# Using a for loop to store values in the list
for i in range(5): # Change 5 to the desired number of iterations
value = i * 2 # Replace this line with the logic to generate or fetch the desired value
my_list.append(value)
# Print the resulting list
print(my_list)
In this example, the for
loop iterates over a range of numbers (0 to 4 in this case), and for each iteration, a value is generated or fetched (in this case, i * 2
), and it’s appended to the my_list
using the append
method.
Comment if you have any doubts or 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.