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 - Insert list in another list
When working with lists in Python, you often need to insert one list into another. Python provides several methods to accomplish this: append(), extend(), insert(), and list concatenation with + operator.
Using append() Method
The append() method adds the entire second list as a single element ?
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9, 10]
first_list.append(second_list)
print("Using append():", first_list)
Using append(): [1, 2, 3, 4, 5, [6, 7, 8, 9, 10]]
Using extend() Method
The extend() method adds each element of the second list individually ?
third_list = [11, 12, 13, 14, 15]
fourth_list = [16, 17, 18, 19, 20]
third_list.extend(fourth_list)
print("Using extend():", third_list)
Using extend(): [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Using insert() Method
The insert() method allows you to insert a list at a specific position ?
numbers = [1, 2, 5, 6]
middle_numbers = [3, 4]
# Insert at index 2
numbers[2:2] = middle_numbers
print("Using slice insertion:", numbers)
# Alternative with insert() for single element
fruits = ['apple', 'banana', 'orange']
fruits.insert(1, 'grape')
print("Using insert():", fruits)
Using slice insertion: [1, 2, 3, 4, 5, 6] Using insert(): ['apple', 'grape', 'banana', 'orange']
Using + Operator (Concatenation)
The + operator creates a new list without modifying the original lists ?
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print("Original list1:", list1)
print("Combined list:", combined)
Original list1: [1, 2, 3] Combined list: [1, 2, 3, 4, 5, 6]
Comparison
| Method | Modifies Original? | Result | Best For |
|---|---|---|---|
append() |
Yes | Nested list | Adding list as single element |
extend() |
Yes | Flat list | Merging list elements |
insert() |
Yes | Insert at position | Adding at specific index |
+ operator |
No | New combined list | Preserving original lists |
Conclusion
Use extend() to merge list elements, append() to add a list as a nested element, and + operator to create new combined lists without modifying originals.
Advertisements
