DEV Community

Lameck Odhiambo
Lameck Odhiambo

Posted on

Python Data Structures

Python features four primary built-in data structures used for storing collections of data: lists, tuples, sets, and dictionaries. Each serves a specific purpose based on whether you need order, unique items, fast key-value lookups, or unchangeable data.

1. Lists

  • Lists are ordered, mutable arrays that can hold a mix of different data types. They track elements by their position, meaning you can access them using zero-based index values
  • Best used for your default choice for a general collection of items that you expect to change, sort, or append to.

Accessing list items through indexing and slicing

  • The syntax for slicing is list_name[start : end : step]

• start: The index where the slice begins (inclusive, defaults to 0).
• end: The index where the slice stops (exclusive, meaning this item is not included; defaults to the end of the list).
• step: The interval or step size between items (defaults to 1)

thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Enter fullscreen mode Exit fullscreen mode
  • This will print the second item in the list.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Enter fullscreen mode Exit fullscreen mode
  • This prints the last item in the list
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Enter fullscreen mode Exit fullscreen mode
  • Returns the third, fourth, and fifth item
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Enter fullscreen mode Exit fullscreen mode
  • This example returns the items from the beginning to, but NOT including, "kiwi"

Unpacking lists

  • List unpacking in Python is a clean, readable syntax that allows you to extract elements from a list (or any iterable) and assign them directly to variables
fruits = ["apple", "banana", "cherry"]

# The number of variables matches the list size
first, second, third = fruits

print(first)   # Output: apple
print(second)  # Output: banana
print(third)   # Output: cherry
Enter fullscreen mode Exit fullscreen mode

Methods used in lists

List Comprehension

  • List comprehension is a concise, readable way to create new lists in Python by iterating over an existing iterable (like a list, tuple, range, or string). It serves as a shorter alternative to traditional for loops.
  • List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Syntax:

newlist = [expression for item in iterable if condition == True]
Enter fullscreen mode Exit fullscreen mode

Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
Enter fullscreen mode Exit fullscreen mode

Condition

  • The condition is like a filter that only accepts the items that evaluate to True.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if x != "apple"]

print(newlist)
Enter fullscreen mode Exit fullscreen mode

Iterable

  • The iterable can be any iterable object, like a list, tuple, set etc.
newlist = [x for x in range(10)]

print(newlist)
Enter fullscreen mode Exit fullscreen mode

Expression

  • The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x.upper() for x in fruits]

print(newlist)
Enter fullscreen mode Exit fullscreen mode

2. Tuples

  • A Python tuple is a built-in collection data type used to store an ordered and immutable (unchangeable) sequence of items. While they are very similar to lists, the core difference is that once a tuple is created, you cannot modify, add, or remove its elements.
  • Tuples are written with round brackets (), and elements are separated by commas. They can hold duplicate values and mixed data types.

Accessing Items

  • Use 0-based indexing or negative indexing.
fruits = ("apple", "banana", "cherry")
print(fruits[0])   # Output: apple
print(fruits[-1])  # Output: cherry (last item)
Enter fullscreen mode Exit fullscreen mode

Slicing

  • Get a sub-part of the tuple using [start:stop:step]
numbers = (1, 2, 3, 4, 5)
print(numbers[1:4])  # Output: (2, 3, 4
Enter fullscreen mode Exit fullscreen mode

)

Tuple Unpacking

  • You can easily extract the elements of a tuple back into individual variables.
coordinates = (4, 10)
x, y = coordinates
print(x)  # Output: 4
print(y)  # Output: 10
Enter fullscreen mode Exit fullscreen mode

3. Sets

  • Sets are built-in data types used to store an unordered collection of unique items. Because sets enforce uniqueness, any duplicate values you attempt to add are automatically removed. Sets themselves are mutable (you can add or remove items), but the individual elements within the set must be of an immutable data type (like strings, integers, or tuples).
# Creating a set with elements
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # Output: {'banana', 'apple', 'cherry'} (Duplicates removed, order varies)

# Creating an empty set
empty_set = set()
Enter fullscreen mode Exit fullscreen mode

Mathematical Set Operations

Python sets natively support classic mathematical operations, which can be called via methods or operators.


set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(set_a | set_b)  # Output: {1, 2, 3, 4, 5, 6}
print(set_a & set_b)  # Output: {3, 4}
print(set_a - set_b)  # Output: {1, 2}
print(set_a ^ set_b)  # Output: {1, 2, 5, 6}
Enter fullscreen mode Exit fullscreen mode

4. Dictionaries

  • A Python dictionary is a built-in, mutable data structure that stores data in key-value pairs. Instead of using a numeric index like a list, dictionaries use unique, immutable keys (like strings, numbers, or tuples) to quickly look up and retrieve values.

1. Creating a Dictionary

  • You can create a dictionary using curly braces {} or the built-in dict() constructor.
# Using curly braces
user = {
    "name": "Alice",
    "age": 30,
    "is_admin": True
}

# Using the dict() constructor
user_alt = dict(name="Alice", age=30, is_admin=True)
Enter fullscreen mode Exit fullscreen mode

2. Accessing Values

  • You can access a value by placing its key inside square brackets []. Alternatively, the .get() method provides a safer way to access values because it returns None (instead of throwing a KeyError) if the key doesn't exist.
# Square bracket lookup
print(user["name"])  # Output: Alice

# Safe lookup with .get()
print(user.get("email"))        # Output: None
print(user.get("email", "N/A")) # Output: N/A (with a fallback default)

Enter fullscreen mode Exit fullscreen mode

3. Adding and Updating Items

  • Because dictionaries are mutable, you can add new key-value pairs or change existing ones using the assignment operator (=) or the .update() method. Keys must be unique; assigning a new value to an existing key will overwrite it.
# Adding a new key-value pair
user["email"] = "alice@example.com"

# Updating an existing value
user["age"] = 31

# Updating multiple values at once
user.update({"age": 32, "city": "New York"})
Enter fullscreen mode Exit fullscreen mode

4. Removing Items

  • Python offers several ways to delete entries based on your specific needs.
# .pop() removes a key and returns its value
age = user.pop("age")

# .popitem() removes and returns the last inserted key-value pair
last_item = user.popitem()

# 'del' statement deletes an item directly
del user["is_admin"]

# .clear() empties the entire dictionary
user.clear() 
Enter fullscreen mode Exit fullscreen mode

5. Iterating Through Dictionaries

  • By default, looping over a dictionary iterates through its keys. You can use specific methods to target keys, values, or both simultaneously.
my_dict = {"a": 1, "b": 2, "c": 3}

# Loop through keys
for key in my_dict.keys():
    print(key)

# Loop through values
for value in my_dict.values():
    print(value)

# Loop through both keys and values (most common)
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, choosing the right built-in data structure in Python depends entirely on your data's requirement for order, mutability, uniqueness, and structural relationship. Selecting the correct collection optimizes memory usage, enhances execution speed, and prevents logical bugs.

Top comments (0)