深度阅读

How to concatenate two lists in Python

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

To concatenate two lists in Python, you can use the concatenation operator + or the extend() method. Here are examples of both methods:

Using the + operator:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
concatenated_list = list1 + list2
print(concatenated_list) # outputs [1, 2, 3, 'a', 'b', 'c']

Using the extend() method:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
list1.extend(list2)
print(list1) # outputs [1, 2, 3, 'a', 'b', 'c']

Both methods will combine the two lists into a single list. Keep in mind that using + operator will return a new list that is the concatenation of the two lists, while the extend() method will modify the first list with the elements of the second list.

相关标签

博客作者

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