Mutable List vs. Immutable Tuples
In Python, both lists and tuples support a range of operations, including indexing, slicing, concatenation, and more. However, there are some differences between the operations that are available for lists and tuples due to their mutability and immutability, respectively.
Python Indexing
Both lists and tuples allow you to access individual elements using their index, starting from 0.
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
print(my_list[0]) # Output: 1
print(my_tuple[1]) # Output: 5
Output
1 5
Python Slicing
Both lists and tuples allow you to extract a subset of elements using slicing.
my_list = [1, 2, 3, 4, 5]
my_tuple = (6, 7, 8, 9, 10)
print(my_list[1:3]) # Output: [2, 3]
print(my_tuple[:3]) # Output: (6, 7, 8)
Output
[2, 3] (6, 7, 8)
Python Concatenation
Both lists and tuples can be concatenated using the “+” operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
tuple1 = (7, 8, 9)
tuple2 = (10, 11, 12)
print(list1 + list2) # Output: [1, 2, 3, 4, 5, 6]
print(tuple1 + tuple2) # Output: (7, 8, 9, 10, 11, 12)
Output
[1, 2, 3, 4, 5, 6] (7, 8, 9, 10, 11, 12)
Note – However, there are some operations that are available only for lists, due to their mutability.
Python Append
Lists can be appended with new elements using the append() method.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Output
[1, 2, 3, 4]
Python Extend
Lists can also be extended with another list using the extend() method.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Output
[1, 2, 3, 4, 5, 6]
Python Remove
Lists can have elements removed using the remove() method.
my_list = [1, 2, 3, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 4]
Output
[1, 3, 4]
Difference Between List and Tuple in Python
Lists and Tuples in Python are two classes of Python Data Structures. The list structure is dynamic, and readily changed whereas the tuple structure is static and cannot be changed. This means that the tuple is generally faster than the list. Lists are denoted by square brackets and tuples are denoted with parenthesis.