Data Structures

Data Structures

Lists and list methods

What Are Lists in Python?

A Python list is a built-in data structure used to store multiple items in a single variable. Lists are ordered and mutable, can hold mixed data types, and are a foundational building block for many data manipulation tasks. If you’re new to Python, consider starting with the Introduction to Python course to get oriented with core concepts.

List Syntax

my_list = [1, 2, 3, “hello”, True]

  • Items are separated by commas.
  • Enclosed in square brackets [].
  • Indexed starting from 0.

Accessing List Items

fruits = [“apple”, “banana”, “cherry”]
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (negative index = from end)

For iterating over lists and controlling flow, see the Loops and Iteration lesson.

Common List Methods

Python provides many built-in methods to manipulate lists:

append(item)

Adds a new item to the end of the list.

fruits.append(“orange”)

insert(index, item)

Inserts an item at a specific position.

fruits.insert(1, “kiwi”) # Inserts “kiwi” at index 1

extend(iterable)

Extends the list by appending elements from another iterable (like another list).

fruits.extend([“mango”, “grape”])

remove(item)

Removes the first occurrence of the specified value.

fruits.remove(“banana”)

pop([index])

Removes and returns the item at the given index (or last item if no index is given).

last_fruit = fruits.pop() # Removes last item

clear()

Removes all items from the list.

fruits.clear()

index(item)

Returns the index of the first occurrence of the specified item.

idx = fruits.index(“apple”)

count(item)

Returns the number of times a value appears in the list.

nums = [1, 2, 2, 3, 2]
print(nums.count(2)) # Output: 3

sort()

Sorts the list in-place (modifies the original list). For ascending order by default.

numbers = [4, 2, 9, 1]
numbers.sort()

Use numbers.sort(reverse=True) for descending.

sorted(list)

Returns a new sorted list without modifying the original.

sorted_numbers = sorted(numbers)

reverse()

Reverses the elements of the list in-place.

numbers.reverse()

copy()

Creates a shallow copy of the list.

new_list = fruits.copy()

Looping Through Lists:

for fruit in fruits:
print(fruit)

List Slicing

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # Output: [1, 2, 3]
print(nums[:3]) # Output: [0, 1, 2]
print(nums[::2]) # Output: [0, 2, 4]

Lists Are Mutable

You can modify individual items:

nums[0] = 100

And delete with del:

del nums[2]

Summary

  • Lists are ordered, mutable, and can hold mixed data types.
  • Access items using indexes.
  • Modify lists with built-in methods like append(), remove(), sort(), and more.
  • Use slicing, loops, and comprehensions for powerful list operations. For a quick review of related basics like variables and data types, see the Variables, Data Types and Operators course.

Tuples and tuple unpacking

What Are Tuples?

A tuple is a built-in data type in Python used to store multiple items in a single, ordered, immutable collection.

  • Like a list, but cannot be changed (immutable) after creation.
  • Often used for fixed data (e.g., coordinates, RGB colors, function returns).

Tuple Syntax

my_tuple = (1, 2, 3)

  • Defined with parentheses () — although parentheses are optional.
  • Elements separated by commas.
  • Can hold mixed data types.

One-item tuple (very important!)

To define a tuple with one item, you must include a comma:

single = (5,) # This is a tuple
not_a_tuple = (5) # This is just an int

Accessing Tuple Elements

Tuples are indexed, just like lists:

colors = (“red”, “green”, “blue”)
print(colors[0]) # red
print(colors[-1]) # blue

Looping Through Tuples

for color in colors:
print(color)

Tuples Are Immutable

You cannot change, add, or remove items from a tuple:

colors[0] = “yellow” # TypeError

Tuple Methods

  • Tuples have fewer methods than lists due to immutability:
  • count(value) – returns the number of times a value appears.
  • index(value) – returns the index of the first matching value.

nums = (1, 2, 2, 3)
print(nums.count(2)) # 2
print(nums.index(3)) # 3

Tuple Unpacking

Tuple unpacking lets you assign values from a tuple to multiple variables in one line.

Basic Unpacking

point = (10, 20)
x, y = point
print(x) # 10 print(y) # 20

The number of variables must match the number of tuple items.

Swapping Variables (Pythonic Way)

a = 5
b = 10
a, b = b, a
print(a, b) # Output: 10 5

No need for a temporary variable!

Unpacking with * (Extended Unpacking)

a, *b = (1, 2, 3, 4)
print(a) # 1
print(b) # [2, 3, 4]

a, *b, c = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5

Tuple Unpacking in Functions

You can return multiple values from a function using a tuple:

def get_user():
return “Alice”, 30 # returns a tuple

name, age = get_user()
print(name) # Alice
print(age) # 30

Summary:

  • Tuples are ordered, immutable sequences.
  • Useful for fixed data or function returns.
  • Use tuple unpacking to assign values in a clean way.
  • Tuples support indexing, looping, and limited methods (count(), index()).

Dictionaries and dictionary methods

What Is a Dictionary?

A dictionary is a collection of key-value pairs, where each key is unique, and each key maps to a specific value. Think of it like a real dictionary: each word (key) has a definition (value).

Dictionary Syntax

my_dict = {
“name”: “Alice”,
“age”: 30,
“is_active”: True
}

  • Keys and values are separated by colons.
  • Pairs are separated by commas.
  • Enclosed in curly braces {}.

Accessing Values

print(my_dict[“name”]) # Output: Alice

Use the key to access the value.

Using get() Method

print(my_dict.get(“name”)) # Alice
print(my_dict.get(“email”, “N/A”)) # N/A if key not found

Safer than bracket access because it avoids KeyError.

Adding & Updating Items

my_dict[“email”] = “alice@example.com” # Add new
my_dict[“age”] = 31 # Update existing

Removing Items

my_dict.pop(“age”) # Removes and returns the value for ‘age’
del my_dict[“is_active”] # Removes key ‘is_active’

Clearing the Dictionary

my_dict.clear() # Removes all items

Dictionary Methods

Here are some of the most commonly used dictionary methods:

Method Description
get(key, default) Returns value for key, or default if key not found
keys() Returns a view object of all keys
values() Returns a view object of all values
items() Returns a view object of (key, value) pairs
update(dict2) Merges dictionary with another dictionary’s key-value pairs
pop(key) Removes and returns the item with the specified key
popitem() Removes and returns the last inserted (key, value) pair
clear() Removes all items from the dictionary

Example: Looping Through a Dictionary

for key in my_dict:
print(key, my_dict[key])

Or with .items()

for key, value in my_dict.items():
print(f”{key}: {value}”)

Check If a Key Exists

if “name” in my_dict:
print(“Found name”)

Dictionary Comprehensions

squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Nesting Dictionaries

users = {
“alice”: {“age”: 25, “email”: “a@example.com”},
&“bob”: {“age”: 30, “email”: “b@example.com”}
}
print(users[“bob”][“email”]) # b@example.com

Summary:

  • Dictionaries store key-value pairs and are unordered (but maintain insertion order from Python 3.7+).
  • Keys must be immutable and unique (e.g., strings, numbers, tuples).
  • Use methods like .get(), .items(), .update(), and .pop() to work with them efficiently.
  • Great for representing structured data, such as JSON, configurations, and more.

Sets and set operations

What Is a Set in Python?

A set is an unordered, mutable, and unindexed collection of unique elements. Sets are great when you need to eliminate duplicates or perform set-based logic.

Set Syntax

my_set = {1, 2, 3, 4}

  • Use curly braces {} or the set() constructor.
  • Duplicate values are automatically removed.

Creating an empty set must use set() — {} creates an empty dictionary, not a set.

empty_set = set()

Example: Duplicates Removed Automatically

nums = {1, 2, 2, 3, 3}
print(nums) # Output: {1, 2, 3}

Common Set Methods

Sets offer a handful of useful methods for performing mathematical-like operations on collections of unique items.

Scroll to Top