How to create a new list from an existing list in Python?

Published on Aug. 22, 2023, 12:17 p.m.

There are several ways to create a new list from an existing list in Python, depending on your requirements. Here are some examples:

  1. Using a for loop or list comprehension to filter and/or transform elements:
old_list = [1, 2, 3, 4, 5]

# create a new list with even elements only
new_list = [x for x in old_list if x % 2 == 0]

print(new_list)  # Output: [2, 4]

In this example, we use a list comprehension to create a new list with only the even elements from the old list.

  1. Using the map() function to apply a function to each element:
old_list = [1, 2, 3, 4, 5]

# create a new list with each element squared
new_list = list(map(lambda x: x**2, old_list))

print(new_list)  # Output: [1, 4, 9, 16, 25]

In this example, we use the map() function with a lambda function to create a new list with each element in the old list squared.

  1. Using slicing to copy the entire list:
old_list = [1, 2, 3, 4, 5]

# create a new list that is a copy of the old list
new_list = old_list[:]

print(new_list)  # Output: [1, 2, 3, 4, 5]

In this example, we create a new list that is a copy of the old list by using slicing to select all elements of the old list.

Tags: