Skip to content

How to store values in a list in Python using for loop

  • by

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:

How to store values in a list in Python using for loop

When you use range, you essentially create a list that Python reiterates through. Thus, for x in range(0, 100) basically 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:

Do 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.

Leave a Reply

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