Python Datastructures

Python Tutorial

Table of Contents

Python Data Structures Tutorial

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.

TypeDescriptionExample
intInteger (whole number, unlimited length)42
floatFloating-point (decimal number)3.14
complexComplex 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:

SystemPrefixExample
Binary0b0b1010 (10)
Octal0o0o12 (10)
Hexadecimal0x0xA (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)
Converting from float to int truncates the decimal part. Converting from int to float adds .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
Challenge: Write a function to compute the area of a circle, rounded to two decimal places. (Area = π × radius²)

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++']
Negative indices count from the end. Slicing returns a new list.

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

MethodDescription
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
Challenge: Write a function to find the largest number in a list.

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')
A single-item tuple must have a trailing comma: ('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)
Tuples are immutable. You cannot add, remove, or change items after creation.
Challenge: Write a function to add an element to a tuple (hint: convert to a list, add, then convert back).

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

MethodDescription
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}.")
Challenge: Write a function to double every letter in a string. For input '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()
Curly braces {} 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

OperationSyntaxDescription
UnionA | B or A.union(B)All elements from both sets
IntersectionA & B or A.intersection(B)Elements in both sets
DifferenceA - B or A.difference(B)Elements in A not in B
Symmetric DifferenceA ^ 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)
Challenge: Write a function that returns the identical items from two sets (their intersection).

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

MethodDescription
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
Challenge: Write a function to merge two dictionaries.

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])
TypecodePython TypeSize (bytes)
‘i’int2 or 4
‘f’float4
‘d’double8

Array Operations

a.append(4)
a.insert(1, 5)
a.remove(2)
a.pop()
print(a[0])

When to Use Arrays vs Lists?

FeatureListArray
Data TypesAny (mixed)Single type
MemoryFlexibleMore efficient
MethodsMany built-inFewer, but faster for numbers

Common Mistakes and Tips

MistakeWhat HappensHow to Fix
Using {} for empty setCreates a dictUse set()
Modifying a tupleTypeErrorConvert to list, modify, convert back
Accessing set by indexTypeErrorIterate instead
Using mutable types as dict/set keysTypeErrorUse 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 collections module for more power.
Keep experimenting! The best way to master data structures is to use them in real code.

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.
Scroll to Top