W3docs

python

How do you concatenate two lists in Python?

Metti in Pratica le Tue Conoscenze

How do you concatenate two lists in Python?

Spiegazione

Concatenating Lists in Python using the + Operator

In Python, one of the most straightforward ways to merge two lists together, that is to concatenate them, is using the + operator. The + operator is Python's built-in solution for concatenation of lists.

Practical Example

For instance, consider the below example:

# Define two lists
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]

# Concatenate the lists
merged_list = list1 + list2

print(merged_list)

When you run this code, the output will be:

['a', 'b', 'c', 1, 2, 3]

Both lists list1 and list2 are merged into merged_list, preserving the order of elements from both lists.

Additional Insights and Best Practices

While using the + operator for concatenating two lists, keep in mind that it creates a new list, leaving the original lists unchanged. If you want to extend a list in-place, you may consider other options like the extend() method in Python.

Here's how to use it:

# Define two lists
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]

# Use extend() method
list1.extend(list2)

print(list1)

The extend() method modifies list1 directly and doesn't create a new list. You may choose to use the + operator or the extend() method depending on whether you need the original lists to remain unchanged or not.

Remember that, while other answers like using the * operator, the append() method, or the concat() method might look plausible, they either do not achieve the same result or do not exist as built-in Python methods for list concatenation.

In conclusion, using the + operator is the correct and the most intuitive way to concatenate two lists in Python. It's a powerful tool you can utilize to enhance the flexibility of your Python code.

Vuoi altro? Fai il quiz completo di Python Basics.

Inizia il Quiz