Table of Contents
Python Data Structures: A Beginner-Friendly Guide
Welcome to your practical guide to Python data structures! In this tutorial, you’ll learn how to use Python’s built-in data structures to store, organize, and manipulate data efficiently. We’ll cover numbers, lists, tuples, strings, sets, dictionaries, and arrays, with clear explanations, real-world examples, and practical tips. By the end, you’ll be able to choose and use the right data structure for your coding projects with confidence.
Learning Goals
- Understand the main data structures in Python and their characteristics
- Learn how to create, access, modify, and iterate through each data structure
- Discover common methods and operations for each type
- Recognize common mistakes and how to avoid them
- Apply your knowledge with practical examples and challenges
1. Python Numbers and Mathematics
Numbers are the foundation of most programs. Python supports several numeric types, each with its own use case.
| Type | Description | Example |
|---|---|---|
int | Integer (whole number, unlimited length) | 42 |
float | Floating-point (decimal number) | 3.14 |
complex | Complex number (real + imaginary) | 2 + 3j |
Checking Types
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 5.42
print(num2, 'is of type', type(num2))
num3 = 8 + 2j
print(num3, 'is of type', type(num3))
This prints the type of each variable. Use type() to check what kind of number you have.
Number Systems
Python supports binary, octal, and hexadecimal numbers using prefixes:
| System | Prefix | Example |
|---|---|---|
| Binary | 0b | 0b1010 (10) |
| Octal | 0o | 0o12 (10) |
| Hexadecimal | 0x | 0xA (10) |
print(0b1101) # 13
print(0xFB + 0b10) # 253
print(0o15) # 13
Type Conversion
Convert between types using int(), float(), and complex():
num1 = int(2.3) # 2
num2 = float(5) # 5.0
num3 = complex('3+5j') # (3+5j)
.0.Random Numbers and Math
Use the random and math modules for advanced operations:
import random
print(random.randrange(10, 20)) # Random integer
print(random.choice(['a', 'b', 'c'])) # Random item
import math
print(math.pi) # 3.141592...
print(math.factorial(6)) # 720
2. Python Lists
Lists are ordered, mutable collections that can store items of any type. They are the most flexible data structure in Python.
Creating Lists
ages = [19, 26, 29]
student = ['Jack', 32, 'CS', [2, 4]]
empty_list = []
Lists can contain different types, including other lists (nested lists).
Accessing Elements
languages = ['Python', 'Swift', 'C++']
print(languages[0]) # Python
print(languages[-1]) # C++ (last element)
print(languages[1:3]) # ['Swift', 'C++']
Adding and Modifying Elements
fruits = ['apple', 'banana']
fruits.append('cherry')
fruits.insert(1, 'orange')
fruits[0] = 'grape' # Modify
Removing Elements
numbers = [2, 4, 7, 9]
numbers.remove(4)
del numbers[0]
popped = numbers.pop() # Removes last
List Methods
| Method | Description |
|---|---|
| append() | Adds an item to the end |
| extend() | Adds items from another iterable |
| insert() | Inserts at a specific index |
| remove() | Removes first occurrence of value |
| pop() | Removes and returns item at index |
| clear() | Removes all items |
| sort() | Sorts the list |
| reverse() | Reverses the list |
| copy() | Returns a shallow copy |
3. Python Tuples
Tuples are ordered, immutable collections. Use them for fixed data that shouldn’t change.
Creating Tuples
numbers = (1, 2, -5)
names = ('James', 'Jack', 'Eva')
mixed = (2, 'Hello', 'Python')
('Hello',)Accessing and Iterating
languages = ('Python', 'Swift', 'C++')
print(languages[0])
for lang in languages:
print(lang)
Tuple Unpacking
tup = (1, 2, 3)
a, b, c = tup
print(a, b, c)
4. Python Strings
Strings are sequences of characters. They are immutable and widely used for text data.
Creating Strings
name = "Python"
message = 'I love Python.'
multiline = """
Never gonna give you up
Never gonna let you down
"""
Accessing and Slicing
greet = 'hello'
print(greet[1]) # 'e'
print(greet[-1]) # 'o'
print(greet[1:4]) # 'ell'
String Operations
- Concatenation:
'Hello' + 'World' - Repetition:
'Hi' * 3 - Membership:
'a' in 'apple' - Length:
len('hello')
Common String Methods
| Method | Description |
|---|---|
| upper() | Convert to uppercase |
| lower() | Convert to lowercase |
| replace() | Replace substring |
| split() | Split into list |
| find() | Find substring index |
| strip() | Remove whitespace |
String Formatting (f-Strings)
name = 'Cathy'
country = 'Canada'
print(f"My name is {name} and I live in {country}.")
'hello', return 'hheelllloo'.
5. Python Sets
Sets are unordered collections of unique elements. Use them for membership tests and removing duplicates.
Creating Sets
student_id = {112, 114, 116, 118, 115}
vowels = {'a', 'e', 'i', 'o', 'u'}
mixed = {'Hello', 101, -2, 'Bye'}
empty_set = set()
{} create an empty dictionary, not a set. Use set() for an empty set.Adding and Removing Elements
numbers = {21, 34, 54}
numbers.add(32)
numbers.update([1, 2, 3])
numbers.discard(21)
Set Operations
| Operation | Syntax | Description |
|---|---|---|
| Union | A | B or A.union(B) | All elements from both sets |
| Intersection | A & B or A.intersection(B) | Elements in both sets |
| Difference | A - B or A.difference(B) | Elements in A not in B |
| Symmetric Difference | A ^ B or A.symmetric_difference(B) | Elements in A or B, not both |
Frozenset
A frozenset is an immutable set. Once created, you cannot add or remove elements.
fs = frozenset([1, 2, 3])
print(fs)
6. Python Dictionaries
Dictionaries store data as key-value pairs. Keys must be unique and immutable; values can be any type.
Creating Dictionaries
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
Accessing, Adding, and Modifying
print(country_capitals["Germany"]) # Berlin
country_capitals["Italy"] = "Rome" # Add
country_capitals["England"] = "Manchester" # Modify
Removing Items
del country_capitals["Germany"]
country_capitals.pop("Canada")
country_capitals.clear() # Remove all
Dictionary Methods
| Method | Description |
|---|---|
| pop() | Removes item by key |
| update() | Adds or updates items |
| clear() | Removes all items |
| keys() | Returns all keys |
| values() | Returns all values |
| items() | Returns key-value pairs |
| get() | Returns value for key |
7. Python Arrays
Arrays are like lists but store only one data type and are more memory-efficient. Use the array module for arrays of numbers, or numpy for advanced numerical work.
Creating Arrays
import array as arr
a = arr.array('i', [1, 2, 3])
| Typecode | Python Type | Size (bytes) |
|---|---|---|
| ‘i’ | int | 2 or 4 |
| ‘f’ | float | 4 |
| ‘d’ | double | 8 |
Array Operations
a.append(4)
a.insert(1, 5)
a.remove(2)
a.pop()
print(a[0])
When to Use Arrays vs Lists?
| Feature | List | Array |
|---|---|---|
| Data Types | Any (mixed) | Single type |
| Memory | Flexible | More efficient |
| Methods | Many built-in | Fewer, but faster for numbers |
Common Mistakes and Tips
| Mistake | What Happens | How to Fix |
|---|---|---|
Using {} for empty set | Creates a dict | Use set() |
| Modifying a tuple | TypeError | Convert to list, modify, convert back |
| Accessing set by index | TypeError | Iterate instead |
| Using mutable types as dict/set keys | TypeError | Use only immutable types (str, int, tuple) |
Summary and Next Steps
- Python offers a variety of data structures for different needs: lists (ordered, mutable), tuples (ordered, immutable), sets (unordered, unique), dictionaries (key-value pairs), and arrays (homogeneous, efficient).
- Choose the right structure based on your data and what you need to do with it.
- Practice using each structure with small projects and challenges.
- Explore advanced topics like list comprehensions, dictionary comprehensions, and the
collectionsmodule for more power.
Next Steps
- Try the challenges above and check your solutions.
- Explore more on skillplayground for hands-on coding practice.
- Learn about advanced data structures and algorithms as your skills grow.
