In Python, Lists, Sets and Tuples store collections but differ in behavior. Lists are ordered, mutable and allow duplicates, suitable for dynamic data. Sets are unordered, mutable and unique, while Tuples are ordered, immutable and allow duplicates, ideal for fixed data.
List in Python
A List is a collection of ordered, mutable elements that can hold a variety of data types. Lists are one of the most commonly used data structures in Python due to their flexibility and ease of use.
Key Characteristics:
- Mutable: Elements can be modified after creation.
- Ordered: Maintains the order of elements.
- Allows Duplicates: Can have multiple occurrences of the same value.
- Heterogeneous: Can store different data types.
# Creating a List
a = [1, 2, 3, 'Python', 3]
# Accessing elements by indexing
print(a[0])
print(a[-1])
# Modifying an element
a[1] = 'Updated'
print(a)
# Appending an element
a.append(4)
# Removing an element
a.remove(3)
# List slicing
print(a[1:3])
Output
1 3 [1, 'Updated', 3, 'Python', 3] ['Updated', 'Python']
Set in Python
A Set is an unordered collection of unique elements. Sets are primarily used when membership tests and eliminating duplicate values are needed.
Key Characteristics:
- Mutable: Elements can be added or removed.
- Unordered: Does not maintain the order of elements.
- Unique Elements: Duplicate values are automatically removed.
- Heterogeneous: Can store different data types.
# Creating a Set
s = {1, 2, 3, 'Python', 3}
print(s)
# Adding elements
s.add(4)
# Removing elements
s.remove(3) # KeyError if the element is not present
# Accessing elements (No indexing because it is unordered)
# for element in s:
# print(element)
Output
{'Python', 1, 2, 3}
Tuple in Python
A Tuple is an ordered, immutable collection of elements. Tuples are often used when data should not be modified after creation.
Key Characteristics:
- Immutable: Once created, elements cannot be modified.
- Ordered: Maintains the order of elements.
- Allows Duplicates: Can contain duplicate values.
- Heterogeneous: Can store different data types.
# Creating a Tuple
tup = (1, 2, 3, 'Python', 3)
# Accessing elements by indexing
print(tup[0])
print(tup[-1])
# Tuple slicing
print(tup[1:4])
# Attempting to modify a tuple (Raises TypeError)
# tup[1] = 'Updated' # Uncommenting this will raise an error
Output
1 3 (2, 3, 'Python')
Key Differences Between Lists, Set and Tuple
Feature | List | Set | Tuple |
|---|---|---|---|
Mutability | Mutable | Mutable (elements must be immutable) | Immutable |
Ordering | Ordered | Unordered | Ordered |
Duplicates | Allows duplicates | No duplicates allowed | Allows duplicates |
Indexing | Supports indexing and slicing | Not supported | Supports indexing and slicing |
Performance | Slower for membership tests | Faster membership tests | Faster than lists |
Use Case | When frequent modifications are required | When uniqueness is needed | When immutability is required |