Create New Lists within a For Loop in Python

04/09/2023

Contents

In this article, you will learn how to create new lists within a for loop in Python.

Creating new lists within a for loop

In Python, we can create new lists within a for loop using various methods.

Using the Append Method

The append() method in Python can be used to add elements to a list. We can create a new list within a for loop and use the append() method to add elements to the list. The syntax for using this method is as follows:

new_list = []
for value in old_list:
    new_list.append(value)

Here is an example:

old_list = [1, 2, 3, 4, 5]
new_list = []
for value in old_list:
    new_list.append(value*2)
print(new_list) # Output: [2, 4, 6, 8, 10]

Using List Comprehension

List comprehension is a concise way of creating new lists in Python. We can create a new list within a for loop using list comprehension. The syntax for using this method is as follows:

new_list = [expression for value in old_list]

Here is an example:

old_list = [1, 2, 3, 4, 5]
new_list = [value*2 for value in old_list]
print(new_list) # Output: [2, 4, 6, 8, 10]

Using the Map Function

The map() function in Python can be used to apply a function to each element of a list. We can create a new list within a for loop using the map() function. The syntax for using this method is as follows:

new_list = list(map(function, old_list))

Here is an example:

old_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x*2, old_list))
print(new_list) # Output: [2, 4, 6, 8, 10]

Using Nested Lists

We can create a nested list within a for loop and then flatten it to create a new list. The syntax for using this method is as follows:

new_list = [value for sublist in old_list for value in sublist]

Here is an example:

old_list = [[1, 2], [3, 4], [5]]
new_list = [value for sublist in old_list for value in sublist]
print(new_list) # Output: [1, 2, 3, 4, 5]