Python From Beginner to Advanced

0% completed

Previous
Next
Python - Joining Lists

Joining lists in Python allows combining multiple lists into a single list. This is useful when working with related data sets that need to be merged. Python provides different ways to join lists, including the + operator, the extend() method, and list unpacking (*).

The method you choose depends on whether you want to create a new list or modify an existing one. The + operator creates a new list without changing the original lists, while extend() modifies one of the lists in place.

1. Joining Lists Using the "+" Operator

The + operator concatenates two or more lists, returning a new list that contains elements from both lists.

Example 1: Using the "+" Operator

Python3
Python3

. . . .

Explanation

  • list_one + list_two creates a new list by concatenating list_one and list_two.
  • The original lists remain unchanged, as a new list is returned.
  • This method is useful when you need a separate merged list without modifying existing data.

2. Joining Lists Using the "extend()" Method

The extend() method adds all elements from another list into the existing list. Unlike +, it modifies the original list instead of creating a new one.

Example 2: Using "extend()"

Python3
Python3

. . . .

Explanation

  • list_one.extend(list_two) modifies list_one in place, adding elements from list_two.
  • The original list_two remains unchanged.
  • This method is more efficient than + when working with large lists since it avoids creating a new list.

3. Joining Lists Using List Unpacking ("*")

List unpacking is a modern and efficient way to join multiple lists using the * operator inside square brackets.

Example 3: Using List Unpacking

Python3
Python3

. . . .

Explanation

  • [*list_one, *list_two] extracts elements from both lists and combines them into a new list.
  • This method is more flexible because you can include additional values or lists.
  • It is faster than + when joining multiple lists at once.

Python provides multiple ways to join lists, each with its own use case. Choosing the right method depends on whether you need to modify an existing list or create a new one, as well as performance considerations for large lists.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next