🔄 Combining Lists

Python provides multiple ways to combine lists, from simple concatenation to more complex merging operations. Understanding these methods is essential for data manipulation and list processing.

# Basic list combination
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)  # [1, 2, 3, 4, 5, 6]

🎯 Combination Methods

Python offers several approaches to combine lists.

Basic Examples

# Different ways to combine lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Using + operator
combined = list1 + list2
print(f"Using +: {combined}")

# Using extend()
list1.extend(list2)
print(f"Using extend(): {list1}")

# Using * operator
repeated = list1 * 2
print(f"Using *: {repeated}")

🔍 Advanced Combinations

Python allows more sophisticated list combinations using built-in functions and modules.

# Advanced combination examples
from itertools import chain

# Using zip()
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(f"Using zip(): {combined}")

# Using chain()
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
chained = list(chain(list1, list2, list3))
print(f"Using chain(): {chained}")

# Using list comprehension
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [x for row in matrix for x in row]
print(f"Flattened matrix: {flattened}")

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent