Skip to content

Instantly share code, notes, and snippets.

@Denilson-Semedo
Last active August 23, 2024 10:25
Show Gist options
  • Save Denilson-Semedo/5e8c936b73025237d692dee296e1bf8f to your computer and use it in GitHub Desktop.
Save Denilson-Semedo/5e8c936b73025237d692dee296e1bf8f to your computer and use it in GitHub Desktop.
Python Data Structures

Python Data Structures

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.

1. List

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.

Syntax:

my_list = [1, 2, 3, "hello", [4, 5]]

Key Methods:

  • 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.

Example Use Cases:

# 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']

2. Tuple

Description: An ordered, immutable (unchangeable) collection that can contain elements of different data types. Tuples are faster than lists due to their immutability.

Syntax:

my_tuple = (1, 2, 3, "hello", [4, 5])

Key Methods:

  • count(x): Returns the number of times x appears in the tuple.
  • index(x): Returns the index of the first occurrence of x.

Example Use Cases:

# 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"}

3. Set

Description: An unordered, mutable collection of unique elements. Sets are useful for membership testing, removing duplicates, and mathematical operations like union and intersection.

Syntax:

my_set = {1, 2, 3, 4}

Key Methods:

  • 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.

Example Use Cases:

# 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]

4. Dictionary

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.

Syntax:

my_dict = {"name": "John", "age": 30, "city": "New York"}

Key Methods:

  • 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.

Example Use Cases:

# 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}")

5. String

Description: A sequence of characters enclosed in single, double, or triple quotes. Strings are immutable.

Syntax:

my_string = "Hello, World!"

Key Methods:

  • 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.

Example Use Cases:

# 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"

Indexing in Strings:

  • 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"
In this example:
  • 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.

Visual Representation of String Indexing:

  • 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.

6. Bytes

Description: A sequence of bytes (8-bit values), often used for binary data. Immutable.

Syntax:

my_bytes = b"Hello, World!"

Key Methods:

  • decode(encoding): Decodes bytes to a string using the specified encoding.
  • hex(): Converts bytes to a hexadecimal string.

Example Use Cases:

# 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'

7. Bytearray

Description: A mutable sequence of bytes.

Syntax:

my_bytearray = bytearray(b"Hello, World!")

Key Methods:

All methods from bytes, plus methods like append(x) and extend(iterable).

Example Use Cases:

# Modifying a bytearray
data = bytearray(b"Hello")
data.append(33)    # bytearray(b'Hello!')
data[0] = 72       # Modify the first byte

Summary of Key Differences:

  • 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment