Python offers several built-in data structures, each serving different purposes and offering unique capabilities. Below is a structured cheatsheet covering Lists, Tuples, Sets, and Dictionaries with explanations, key methods, and use cases.
Description: An ordered, mutable (changeable) collection that can contain elements of different data types. Lists are dynamic, meaning they can grow and shrink in size.
my_list = [1, 2, 3, "hello", [4, 5]]
append(x):
Adds element x to the end.extend(iterable):
Adds all elements from an iterable.insert(i, x):
Inserts element x at index i.remove(x):
Removes the first occurrence of x.pop([i]):
Removes and returns the element at index i (default is the last item).index(x):
Returns the index of the first occurrence of x.sort():
Sorts the list in place.reverse():
Reverses the elements of the list in place.
# Creating and manipulating a list
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana") # ['apple', 'cherry', 'orange']
fruits.sort() # ['apple', 'cherry', 'orange']
Description: An ordered, immutable (unchangeable) collection that can contain elements of different data types. Tuples are faster than lists due to their immutability.
my_tuple = (1, 2, 3, "hello", [4, 5])
count(x):
Returns the number of times x appears in the tuple.index(x):
Returns the index of the first occurrence of x.
# Creating and using a tuple
dimensions = (1920, 1080)
width = dimensions[0] # 1920
height = dimensions[1] # 1080
# Tuples can be used as keys in dictionaries (unlike lists)
location = {(10.0, 20.0): "Home"}
Description: An unordered, mutable collection of unique elements. Sets are useful for membership testing, removing duplicates, and mathematical operations like union and intersection.
my_set = {1, 2, 3, 4}
add(x):
Adds element x to the set.remove(x):
Removes element x from the set. Raises an error if x is not present.discard(x):
Removes element x if it is present.pop():
Removes and returns an arbitrary set element.union(set):
Returns the union of sets.intersection(set):
Returns the intersection of sets.difference(set):
Returns the difference of sets.issubset(set):
Checks if the set is a subset of another set.
# Creating and manipulating a set
even_numbers = {2, 4, 6, 8}
odd_numbers = {1, 3, 5, 7}
all_numbers = even_numbers.union(odd_numbers) # {1, 2, 3, 4, 5, 6, 7, 8}
common_numbers = even_numbers.intersection({4, 5, 6}) # {4, 6}
# Removing duplicates from a list using a set
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list)) # [1, 2, 3, 4, 5]
Description: An unordered, mutable collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples). Values can be any data type.
my_dict = {"name": "John", "age": 30, "city": "New York"}
get(key[, default]):
Returns the value for key if key is in the dictionary, else default.keys():
Returns a view object displaying a list of all keys.values():
Returns a view object displaying a list of all values.items():
Returns a view object displaying a list of dictionary's key-value tuple pairs.pop(key):
Removes and returns the value associated with key.update(dict):
Updates the dictionary with the key-value pairs from another dictionary or an iterable of pairs.
# Creating and using a dictionary
person = {"name": "Alice", "age": 28, "city": "Paris"}
age = person["age"] # 28
person["email"] = "alice@example.com" # Add a new key-value pair
person.update({"age": 29}) # Update an existing value
# Iterating over keys and values
for key, value in person.items():
print(f"{key}: {value}")
Description: A sequence of characters enclosed in single, double, or triple quotes. Strings are immutable.
my_string = "Hello, World!"
upper():
Converts all characters to uppercase.lower():
Converts all characters to lowercase.strip():
Removes leading and trailing whitespaces.replace(old, new):
Replaces occurrences of old with new.split(delimiter):
Splits the string into a list using delimiter.join(iterable):
Joins elements of iterable into a string, separated by the string's value.
# String manipulation
greeting = " Hello, World! "
greeting = greeting.strip().upper() # "HELLO, WORLD!"
# Splitting and joining strings
csv_data = "apple,banana,cherry"
fruits = csv_data.split(",") # ['apple', 'banana', 'cherry']
new_string = " ".join(fruits) # "apple banana cherry"
- Strings in Python are indexed, allowing you to access individual characters using their positions.
- Indexes start at 0 for the first character and go up to n-1 for the last character.
- Negative indexing starts from -1 for the last character and goes to -n for the first character. Example: Python Strings Operations
# Creating a string
string = "Welcome to Andorigna"
print(string) # "Welcome to Andorigna"
# Printing the first character
print(string[0]) # "W"
# Printing the last character
print(string[-1]) # "a"
- The string "Welcome to Andorigna" is created.
- The first character (W) is accessed using the index 0.
- The last character (a) is accessed using the index -1.
- Positive indexing (left to right) starts from 0.
- Negative indexing (right to left) starts from -1.
A | N | D | O | R | I | G | N | A |
---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
-9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
This representation shows how each character in the string can be accessed using its index.
Description: A sequence of bytes (8-bit values), often used for binary data. Immutable.
my_bytes = b"Hello, World!"
decode(encoding):
Decodes bytes to a string using the specified encoding.hex():
Converts bytes to a hexadecimal string.
# Encoding and decoding bytes
text = "Hello, World!"
encoded_text = text.encode("utf-8") # b'Hello, World!'
decoded_text = encoded_text.decode("utf-8") # "Hello, World!"
# Bytes manipulation
data = b'\x00\xFF'
hex_string = data.hex() # '00ff'
Description: A mutable sequence of bytes.
my_bytearray = bytearray(b"Hello, World!")
All methods from bytes, plus methods like append(x) and extend(iterable).
# Modifying a bytearray
data = bytearray(b"Hello")
data.append(33) # bytearray(b'Hello!')
data[0] = 72 # Modify the first byte
- Lists vs Tuples: Lists are mutable; tuples are immutable.
- Sets vs Lists/Tuples: Sets are unordered and only allow unique elements.
- Dictionaries: Use key-value pairs for efficient lookups.
- Strings: Immutable sequences of characters, useful for text manipulation.
- Bytes/Bytearrays: For handling binary data; bytearray is mutable.