Python Data Structures
Last updated:
- lists - mutable ordered collection
- tuples - immutable ordered collection
- sets - mutable unordered collection of unique elements
Lists
Mutable, ordered collection of elements - can store elements of different data types, including integers, strings, and even other lists.
Creating a List
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = ['apple', 1, 'banana', 2]
List Methods and Operations
fruits = ['apple', 'banana', 'cherry']
print(fruits[1]) # Output: banana
Adding elements - the append() method:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Removing elements - the remove() method:
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry']
Slicing - extract a portion of a list:
numbers = [1, 2, 3, 4, 5]
sliced_numbers = numbers[1:4]
print(sliced_numbers) # Output: [2, 3, 4]
Tuples
Immutable, ordered collection of elements - once created, its contents cannot be modifed.
Creating a Tuple
fruits = ('apple', 'banana', 'cherry')
coordinates = (3, 4, 5)
Tuple Methods and Operations
fruits = ('apple', 'banana', 'cherry')
print(fruits[1]) # Output: banana
Counting elements - the count() method:
numbers = (1, 2, 3, 2, 4, 2)
count_of_twos = numbers.count(2)
print(count_of_twos) # Output: 3
Finding the index - the index() method:
fruits = ('apple', 'banana', 'cherry')
index_of_banana = fruits.index('banana')
print(index_of_banana) # Output: 1
Sets
Unordered, mutable collection of unique elements - duplicate elements are not allowed.
Creating a Set
fruits = {'apple', 'banana', 'cherry'}
numbers = set([1, 2, 3, 4, 5])
Set Methods and Operations
Adding elements - the add() method:
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
Removing elements - the remove() method:
fruits = {'apple', 'banana', 'cherry'}
fruits.remove('banana')
print(fruits) # Output: {'apple', 'cherry'}
Union - use the union() method or the | operator: |
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# or
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
Intersection - the intersection() method or the & operator:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# or
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
Difference - the difference() method or the - operator:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
# or
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}