Python List

List concatenation

Using the + operator, allows you to merge two or more lists into a single new list. It's like combining two shopping lists into one bigger list.

Here's how it works:

fruits = ["apple", "banana"]
vegetables = ["carrot", "pea"]

combined_list = fruits + vegetables
print(combined_list)  # Output: ["apple", "banana", "carrot", "pea"]

In this example, the + operator combines the elements of fruits and vegetables into a new list named combined_list. The order is preserved, with elements from fruits appearing first.


Key Points

  • The + operator creates a new list. It doesn't modify the original lists.
  • You can concatenate multiple lists at once using the same syntax.

list1 = [1, 2, 3]
list2 = [4, 5]
list3 = ["a", "b"]

combined_list = list1 + list2 + list3
print(combined_list)  # Output: [1, 2, 3, 4, 5, "a", "b"]


Things to consider

  • Concatenation works with any lists containing compatible data types. Mixing lists with different data types (e.g., integers and strings) will result in a combined list with all elements.
  • For specific use cases where you want to modify an existing list instead of creating a new one, consider using the extend() method. It appends elements from another list to the end of the original list.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What will be the output of the following code: fruits = ["apple", "banana"]; vegetables = ["carrot", "pea"]; combined_list = fruits + vegetables; print(combined_list)?

["carrot", "pea"]
["apple", "banana", "carrot", "pea"]
["carrot", "pea", "apple", "banana"]
["apple", "banana"]
Check Answer

Does the + operator modify the original lists when combining them?

No, it creates a new list.
Yes, it modifies the original lists.
It removes the original lists.
It copies the original lists.
Check Answer

What will combined_list = list1 + list2 + list3 produce if list1 = [1, 2, 3], list2 = [4, 5], list3 = ["a", "b"]?

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, "a", "b"]
[1, 2, 3, "a", "b", 4, 5]
[1, 2, 3, 5, 4, "a", "b"]
Check Answer

What happens when you concatenate lists of different data types?

An error occurs.
The lists cannot be concatenated.
It creates a combined list with all elements.
Only compatible data types are combined.
Check Answer

Which method would you use to modify an existing list instead of creating a new one?

merge()
add()
append()
extend()
Check Answer