深度阅读

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

作者
作者
2023年08月22日
更新时间
12.02 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。