Add Values into Empty List Using For Loop - Python
Lists are versatile data structures that allow you to store and manipulate collections of items. The simplest way to add values to an empty list is by using append() method. This method adds a single item to the end of the list.
a = []
# Loop through a range of numbers and add them to the list
for i in range(5):
a.append(i)
# Print the list
print(a)
Output
[0, 1, 2, 3, 4]
Other methods that we can use to add values into an empty list using a python for loop are :
Table of Content
Using List Comprehension
List comprehension is a more compact way to create and add values to a list in one step. This method is concise and often preferred for its readability and efficiency.
a = [i for i in range(5)]
# Print the list
print(a)
Output
[0, 1, 2, 3, 4]
Using extend() inside a For Loop
Another method to add values is by using extend() method. This method is used to add multiple values at once to a list.
a = []
# Create another list of values
values = [0, 1, 2, 3, 4]
# Use extend to add all values to a
a.extend(values)
# Print the list
print(a)
Output
[0, 1, 2, 3, 4]
Using += Operator
The += operator allows us to add items from one list to another. This can be useful when you want to add multiple values.
a = []
# Add values using the += operator
a += [0, 1, 2, 3, 4]
# Print the list
print(a)
Output
[0, 1, 2, 3, 4]
Using a While Loop
We can also use a while loop to add values to a list. This method gives us more control over the loop but is a bit more complex.
# Create an empty list
a = []
# Initialize the counter
i = 0
# Use a while loop to add values
while i < 5:
a.append(i)
i += 1
# Print the list
print(a)
Output
[0, 1, 2, 3, 4]
Using insert() inside a For Loop
The insert() method allows us to add values to a specific position in the list. While it is not as commonly used to append values at the end of the list, it can still be useful when we want to control where the values are placed.
a = []
# Loop through a range of numbers and insert them at the beginning
for i in range(5):
a.insert(0, i)
# Print the list
print(a)
Output
[4, 3, 2, 1, 0]