Add Values into an Empty List from Python For Loop
Last Updated :
15 Feb, 2024
Working with Python often involves the use of lists, a versatile data structure that allows you to store and manipulate collections of items. One common scenario is populating an empty list with values generated during a loop. In this article, we will explore four simple and commonly used methods to achieve this. Each method will be accompanied by code examples to illustrate its implementation.
How To Add Values Into An Empty List From A For Loop?
Below, are the methods of How To Add Values Into An Empty List From A For Loop in Python
Add Values Into An Empty List From A For Loop Using Append() Method
In this example, below, code uses the `append` method to add values from a loop to an initially empty list. It iterates through the range of 0 to 4 (5 exclusive) and appends each value to the list, resulting in the list `[0, 1, 2, 3, 4]`.
Python3
empty_list = []
for i in range ( 5 ):
empty_list.append(i)
print (empty_list)
|
Add Values Into An Empty List From A For Loop Using List Comprehension
In this example, below code employs list comprehension to create a list with values from the range 0 to 4 (5 exclusive). It generates the list `[0, 1, 2, 3, 4]` in a concise single line.
Python3
empty_list = [i for i in range ( 5 )]
print (empty_list)
|
Add Values Into An Empty List From A For Loop Using extend() Method
In this example, below code utilizes the `extend` method to populate an initially empty list within a loop. It appends each value from the range 0 to 4 (5 exclusive) to the list, resulting in the list `[0, 1, 2, 3, 4]`.
Python3
empty_list = []
for i in range ( 5 ):
empty_list.extend([i])
print (empty_list)
|
Add Values Into An Empty List From A For Loop Using the + Operator
In this example, below code uses the `+` operator to concatenate an initially empty list with individual values from the range 0 to 4 (5 exclusive). It results in the list `[0, 1, 2, 3, 4]`, though this method may be less efficient for larger lists due to the creation of multiple lists in each iteration.
Python3
empty_list = []
for i in range ( 5 ):
empty_list = empty_list + [i]
print (empty_list)
|
Conclusion
Populating an empty list from a for loop is a common task in Python, and there are multiple ways to achieve it. The choice between these methods often depends on the specific requirements of your code and personal preferences. The append
method is widely used for its simplicity, while list comprehensions provide a concise and readable alternative. The extend
method and the +
operator offer additional options, though they may be less commonly used in this context.
Share your thoughts in the comments
Please Login to comment...