Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Combine list with other list elements
When it is required to combine list with other list elements, Python provides several methods. The most common approaches are using iteration with append(), the extend() method, or the + operator.
Method 1: Using Loop with append()
This method iterates through the second list and appends each element to the first list ?
my_list_1 = [12, 14, 25, 36, 15]
print("The first list is :")
print(my_list_1)
my_list_2 = [23, 15, 47, 12, 25]
print("The second list is :")
print(my_list_2)
for element in my_list_2:
my_list_1.append(element)
print("The result is :")
print(my_list_1)
The first list is : [12, 14, 25, 36, 15] The second list is : [23, 15, 47, 12, 25] The result is : [12, 14, 25, 36, 15, 23, 15, 47, 12, 25]
Method 2: Using extend()
The extend() method adds all elements from one list to another in a single operation ?
my_list_1 = [12, 14, 25, 36, 15]
my_list_2 = [23, 15, 47, 12, 25]
print("Before combining:")
print("List 1:", my_list_1)
print("List 2:", my_list_2)
my_list_1.extend(my_list_2)
print("After combining with extend():")
print(my_list_1)
Before combining: List 1: [12, 14, 25, 36, 15] List 2: [23, 15, 47, 12, 25] After combining with extend(): [12, 14, 25, 36, 15, 23, 15, 47, 12, 25]
Method 3: Using + Operator
The + operator creates a new list without modifying the original lists ?
my_list_1 = [12, 14, 25, 36, 15]
my_list_2 = [23, 15, 47, 12, 25]
combined_list = my_list_1 + my_list_2
print("Original List 1:", my_list_1)
print("Original List 2:", my_list_2)
print("Combined List:", combined_list)
Original List 1: [12, 14, 25, 36, 15] Original List 2: [23, 15, 47, 12, 25] Combined List: [12, 14, 25, 36, 15, 23, 15, 47, 12, 25]
Comparison
| Method | Modifies Original? | Performance | Best For |
|---|---|---|---|
append() loop |
Yes | Slower | Learning purposes |
extend() |
Yes | Fast | In-place combining |
+ operator |
No | Fast | Creating new combined list |
Conclusion
Use extend() when you want to modify the original list in-place. Use the + operator when you need to preserve original lists and create a new combined list.
Advertisements
