Open In App

Creating A New List For Each For Loop

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Example using list comprehension
original_list = [1, 2, 3, 4, 5]
new_lists = [[item * i for i in range(1, 4)] for item in original_list]
 
# Output
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




# Example using a dictionary of lists
 
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




# Example using enumerate and list concatenation
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)])
 
# Output
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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads