Creating A New List For Each For Loop
Last Updated :
26 Feb, 2024
The capacity to effectively arrange and modify data is essential while dealing with it. This article will discuss how to use Python’s for loop, which is a useful tool for iterating over items, to generate new lists.
Creating A New List For Each For Loop in Python
Below are some of the approaches by which we can create a new list for each for loop in Python:
Using List Comprehension
In this example, a new list (new_lists
) is created using list comprehension, where each element of the original list (original_list
) is multiplied by values ranging from 1 to 3, resulting in a nested list structure. The output displays the newly generated lists for each element in the original list.
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ]
new_lists = [[item * i for i in range ( 1 , 4 )] for item in original_list]
print (new_lists)
|
Output
[[1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12], [5, 10, 15]]
Using map
and lambda
function
In this example, a list of lists (all_lists
) is generated using the map
function and a lambda expression, where each element is created by multiplying the corresponding value from the range() with values ranging from 0 to 2. The output displays the nested lists representing the result of these operations.
Python3
all_lists = list ( map ( lambda i: [i * j for j in range ( 3 )], range ( 5 )))
print (all_lists)
|
Output
[[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6], [0, 4, 8]]
Using Enumerate and List Concatenation
In this example, a new list (new_lists
) is constructed using a for loop with enumerate
, where each element of the original list (original_list
) is multiplied by values ranging from 1 to 3. The resulting lists are appended to the new_lists
through list concatenation.
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ]
new_lists = []
for index, item in enumerate (original_list):
new_lists.append([item * i for i in range ( 1 , 4 )])
print (new_lists)
|
Output
[[1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12], [5, 10, 15]]
Conclusion
Manipulating data and carrying out activities inside the loop are made more flexible by creating a new list for each iteration of the for loop. The methods offered provide several means of doing this, accommodating a range of Python programming contexts and needs.
Share your thoughts in the comments
Please Login to comment...