Python Data Structures — learn by examples

Explore lists, tuples, dictionaries, sets, and strings. Jump straight to a topic below.

DATA STRUCTURE IN PYTHON

So far, you have only stored small pieces of data in a variable, such as an integer, Boolean, or string.

But what if you need to work with more complex information, like a list of people or a collection of companies? This is where data structures come in. Data structures allow you to organize and arrange your data efficiently, making it easier to perform operations on them.

Python provides several built-in data structures, including List, Dictionary, Tuple, and Set. These are considered non-primitive data structures because they are treated as objects. We will explore these in detail shortly.

In addition to built-in structures, Python allows you to create your own custom data structures, such as Stacks, Queues, and Trees. Each data structure can be tailored to solve a specific problem or optimize an existing solution for better performance.

Mutability and Immutability

Data structures can be either mutable or immutable. Mutability means that the data inside the structure can be changed — you can update, add, or delete items as needed. For example, a list is mutable.

On the other hand, immutable data structures cannot be modified once they are created. The tuple is an example of an immutable data structure. Once its data is set, it cannot be changed, which can help preserve data integrity and improve performance in certain cases.

DICTIONARIES IN PYTHON

🗂️ Python Dictionary

A dictionary in Python is an ordered collection (from Python 3.7 onwards) of items stored as key/value pairs. Each key is a unique identifier associated with a value.

For example, if we want to store countries and their capitals, we can create a dictionary where the country names are keys and capitals are values.

Creating a Dictionary

capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
print(capital_city)

Here:

    Keys: "Nepal", "Italy", "England"

    Values: "Kathmandu", "Rome", "London"

    Keys and values can be of different types.

Example 1: Dictionary with Integer Keys

numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)

Adding Elements

capital_city["Japan"] = "Tokyo"
print(capital_city)

Changing Values

student_id = {112: "Kyle", 113: "Maria"}
student_id[112] = "Stan"
print(student_id)

Accessing Elements

print(capital_city["Italy"]) # Output: Rome
# Accessing a non-existing key will raise an error # print(capital_city["Germany"]) # KeyError

Removing Elements

student_id = {111: "Alice", 112: "Bob"}
del student_id[111] # removes the key 111
print(student_id)
# del student_id # deletes the entire dictionary

Dictionary Methods

Dictionaries come with many useful methods such as keys(), values(), items(), get(), and update().

Membership Test

squares = {1: 1, 2: 4, 3: 9}
print(2 in squares) # True
print(5 in squares) # False

Iterating Through a Dictionary

squares = {1: 1, 2: 4, 3: 9}
for key in squares:
print(f"Key: {key}, Value: {squares[key]}")

📌 Try Yourself:

[Add your "Try Yourself" interactive Python editor here]

🔗 More Resources

💡 Note: You can create dictionaries with mixed key and value types. For example:

random_dict = {"name": "Alice", 1: [10, 20, 30], "is_student": True}
print(random_dict)

📋 Python Lists

Lists are used to store multiple items in a single variable. For example, if we want to record the ages of 5 students, we can create a list instead of separate variables.

Creating a List

numbers = [10, 20, 30]
print(numbers)

A list can contain items of different types, such as integers, floats, and strings:

mixed_list = [10, "Python", 5.5, True]
print(mixed_list)

Accessing List Elements

Each item has an index starting from 0:

languages = ["Python", "Dart", "JavaScript"]
print(languages[0]) # Python
print(languages[-1]) # JavaScript

Slicing Lists

my_list = [10, 20, 30, 40, 50]
print(my_list[2:5]) # [30, 40, 50]
print(my_list[3:]) # [40, 50]
print(my_list[:]) # [10, 20, 30, 40, 50]

Adding Elements

Using append() to add a single item:

numbers.append(40)
print(numbers) # [10, 20, 30, 40]

Using extend() to merge another list:

even_numbers = [2, 4, 6]
numbers.extend(even_numbers)
print(numbers) # [10, 20, 30, 40, 2, 4, 6]

Changing List Items

numbers[0] = 100
print(numbers) # [100, 20, 30, 40, 2, 4, 6]

Removing Elements

Using del:

del numbers[2]
print(numbers)

Using remove():

numbers.remove(4)
print(numbers)

Iterating Through a List

for item in numbers:
print(item)

List Comprehension

Creates lists in a concise way:

squares = [x**2 for x in range(1,6)]
print(squares) # [1, 4, 9, 16, 25]

📌 Try Yourself: [Add interactive editor here]


🔒 Python Tuples

Tuples are similar to lists but are immutable. Once created, elements cannot be changed.

Creating a Tuple

my_tuple = (10, 20, "Python")
print(my_tuple)

Tuple with One Element

var1 = ("hello",)
print(type(var1)) # <class 'tuple'>
var2 = ("hello")
print(type(var2)) # <class 'str'>

Accessing Tuple Elements

Using indexing:

letters = ('a','b','c','d','e','f')
print(letters[0]) # 'a'
print(letters[-1]) # 'f'
print(letters[-3]) # 'd'

Tuple Methods

Only a few methods are available:

my_tuple = ('apple', 'banana', 'apple')
print(my_tuple.count('apple')) # 2
print(my_tuple.index('banana')) # 1

📌 Try Yourself: [Add interactive editor here]

🔗 More Resources

🟢 Python Sets

A set is a collection of unique data. Elements of a set cannot be duplicated. For example, we can store student IDs in a set since they are unique.

Creating a Set

We create sets using curly braces {} or the set() function:

numbers = {1, 2, 3, 4}
mixed_set = {1, "Python", 3.5, (2,3)}
print(numbers)
print(mixed_set)

Empty Set

empty_set = set()
empty_dict = {}
print(type(empty_set)) # <class 'set'>
print(type(empty_dict)) # <class 'dict'>

Duplicate Items

numbers = {1, 2, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4} duplicates removed

Adding Items

numbers.add(5)
print(numbers)

Updating a Set

tech_companies = {"Google", "Apple"}
companies = {"Microsoft"}
companies.update(tech_companies)
print(companies) # {'Microsoft', 'Google', 'Apple'}

Removing Elements

languages = {"Python", "Java", "C++"}
languages.discard("Java")
print(languages)

Set Built-in Functions

numbers = {1, 2, 3, 4}
print(len(numbers)) # 4
print(max(numbers)) # 4
print(min(numbers)) # 1

Set Operations

Union, Intersection, Difference, Symmetric Difference:

A = {1, 2, 3}
B = {2, 3, 4}
print(A | B) # Union {1, 2, 3, 4}
print(A & B) # Intersection {2, 3}
print(A - B) # Difference {1}
print(A ^ B) # Symmetric Difference {1, 4}

Check Equality

A = {1, 2, 3}
B = {3, 2, 1}
if A == B:
print("Set A and Set B are equal")

🔗 More Resources

🔤 Python Strings

In computer programming, a string is a sequence of characters. For example, "hello" contains 'h', 'e', 'l', 'l', 'o'. Strings can be enclosed in single or double quotes in Python.

Creating Strings

string1 = "Python Programming"
name = "Python"
message = "I love Python"
print(string1)
print(name)
print(message)

Accessing String Characters

Three ways to access string characters:

# Indexing
str1 = "Python"
print(str1[0]) # 'P'
print(str1[-1]) # 'n'
# Slicing
print(str1[1:4]) # 'yth'

Immutability

str1 = "Hello"
# str1[0] = 'J' <-- This will give an error
str1 = "Jello" # Reassigning variable is allowed

Multiline Strings

multiline = """This is a
multiline string
in Python"""
print(multiline)

String Operations

# Compare Strings
str1 = "Python"
str2 = "Python"
print(str1 == str2) # True
# Concatenate Strings
greet = "Hello, "
name = "Tawfiq"
print(greet + name) # "Hello, Tawfiq"

Iterate Through a String

for ch in "Python":
print(ch)

String Length & Membership

str1 = "Python"
print(len(str1)) # 6
print("P" in str1) # True

Escape Sequences

text = "He said, \"Python is awesome\""
text2 = 'It\'s Python'

Python f-Strings

name = "Tawfiq"
country = "Tanzania"
print(f'{name} is from {country}') # Tawfiq is from Tanzania

🔗 More Resources

💻 Python Practice Tasks

  1. Create a list of integers from user input and compute the sum.
  2. Create a tuple of your 5 favorite books and print each book on a new line.
  3. Create a dictionary to store a person's name, age, and favorite color from user input and print it.
  4. Create two sets of integers from user input and find the common elements.
  5. Store a list of words and use list comprehension to keep only words with an odd number of characters.

📝 Test Your Code