0% found this document useful (0 votes)
2 views11 pages

Python Data Structures

This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets, explaining their characteristics and use cases. It details how to create, access, and manipulate these structures, along with comparisons of their features. Additionally, it includes examples and a quick reference cheatsheet for each data structure.

Uploaded by

chaitanyakommu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Python Data Structures

This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets, explaining their characteristics and use cases. It details how to create, access, and manipulate these structures, along with comparisons of their features. Additionally, it includes examples and a quick reference cheatsheet for each data structure.

Uploaded by

chaitanyakommu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BEGINNER SERIES · SESSION 2

Python
Data Structures
for Beginners
List Tuple Dictionary Set

Organize and manage your data like a pro

Python Programming · Data Structures · Lists · Tuples · Dictionaries · Sets


What are Data Structures? Dictionaries
01 04
Why we need them Key-value pair storage

WHAT
WE'LL Lists Sets

COVER 02
Ordered, mutable collections
05
Unique, unordered elements

Python Data Structures


Tuples Comparison & Use Cases
03 06
Ordered, immutable collections When to use which structure
01 What are Data Structures?

A data structure is a way to organize and store data in a computer so it can be accessed and modified efficiently.

List → Shopping Cart Tuple → GPS Coordinates

An ordered sequence of items you can add to, remove from, or


Fixed data that never changes: (lat, long) stays constant.
change.

Dictionary → Phone Book Set → Unique Tags

Look up a value (number) by a unique key (name). A collection of labels where duplicates are automatically removed.
02 Lists [ ]

Ordered Mutable Duplicates Indexed

Items keep their position Can add, remove, change Allows repeated values Access by index [0, 1, 2…]

list_demo.py Common List Methods

# Creating a list .append(x) Add x to end


fruits = ['apple', 'banana', 'cherry']
.insert(i,x) Insert x at index i
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', True, 3.14] .remove(x) Remove first x

.pop() Remove last item


# Accessing elements
.sort() Sort in place
print(fruits[0]) # apple
print(fruits[-1]) # cherry .len(list) Count elements

print(fruits[1:3]) # ['banana','cherry']
.reverse() Reverse the list
03 Tuples ( )

Ordered Immutable Duplicates Faster

Items keep position Cannot be changed Allows repeated values Quicker than lists

tuple_demo.py List vs Tuple

# Creating tuples List [ ] Tuple ( )


point = (10, 20)
Mutable Immutable
rgb = (255, 128, 0)
single = (42,) # comma needed! Slower Faster

More methods Fewer methods


# Accessing
print(point[0]) # 10 [ ] brackets ( ) brackets
print(rgb[1:]) # (128, 0)
Data changes Fixed data

# Tuple unpacking Shopping cart GPS coords


x, y = point
print(x, y) # 10 20
04 Dictionaries { key: value }

Key-Value Mutable Fast Lookup Unique Keys

Each item is a pair Add, edit, delete pairs O(1) access by key No duplicate keys

dict_demo.py Dictionary Methods

# Creating a dictionary .keys() Returns all keys


student = {
'name': 'Alice', .values() Returns all values

'age': 20,
.items() Returns key-value pairs
'grade': 'A'
} .get(k) Safe value lookup

.update(d) Merge another dict


# Accessing values
print(student['name']) # Alice .pop(k) Remove & return value
print([Link]('age'))# 20
.clear() Empty the dictionary

# Adding / Updating
05 Sets { }

Unordered No Duplicates Mutable Set Math

No fixed position Unique values only Can add/remove items Union, intersect, diff

set_demo.py Set Methods

# Creating sets .add(x) Add element x


colors = {'red', 'blue', 'green'}
nums = {1, 2, 3, 2, 1} # → {1,2,3} .remove(x) Remove (error if missing)

empty = set() # NOT {} (that's dict)


.discard(x) Remove (no error)

# Set operations .pop() Remove random item

a = {1, 2, 3, 4}
.union(s) Combine two sets
b = {3, 4, 5, 6}
print(a | b) # Union: {1,2,3,4,5,6} .intersection(s) Common elements
print(a & b) # Intersect: {3,4}
.difference(s) Items only in this set
print(a - b) # Difference: {1,2}
print(a ^ b) # Symm diff: {1,2,5,6}
06 Comparison & When to Use Each

Feature List [ ] Tuple ( ) Dict { } Set { }

Ordered Yes Yes Yes* No

Mutable Yes No Yes Yes

Duplicates Yes Yes Keys No

Syntax [] () { k:v } { } / set()

Indexed Yes Yes By key No

Use case Shopping cart Coordinates Profile Unique tags

Performance Medium Fastest Fast lookup Fast ops

* Python 3.7+ dictionaries maintain insertion order


BONUS Nested & Combined Data Structures

List of Dictionaries Dictionary of Lists

students = [ school = {
{'name': 'Alice', 'grade': 90}, 'science': ['Alice','Bob'],
{'name': 'Bob', 'grade': 85}, 'math': ['Carol','Dave'],
{'name': 'Carol', 'grade': 92}, 'art': ['Eve'],
] }

# Access nested data # Add to a nested list


print(students[0]['name']) # Alice school['math'].append('Frank')

# Loop through # Loop through dict


for s in students: for dept, pupils in [Link]():
print(s['name'], s['grade']) print(dept, ':', pupils)
# Alice 90 # science : ['Alice', 'Bob']
# Bob 85 # math : ['Carol','Dave','Frank']
Python Data Structures — Quick Reference Cheatsheet

LIST [ ] TUPLE ( ) DICTIONARY { } SET { }

fruits = ['a','b','c'] pt = (10, 20) d = {'a': 1, 'b': 2} s = {1, 2, 3}

[Link]('d') pt[0] → 10 d['a'] → 1 [Link](4)

[Link]('a') x, y = pt d['c'] = 3 [Link](1)

fruits[0] → 'b' len(pt) → 2 [Link]() / .values() s | t → union

len(fruits) → 3 [Link](10) → 1 [Link]('x', 0) → 0 s & t → intersect

[Link]() [Link](20) → 1 del d['b'] s - t → difference

2 in fruits → False # Immutable! 'a' in d → True 3 in s → True

type(x) checks the type · len(x) counts items · in operator checks membership · for loop iterates all structures
What You Learned Today!

Lists
What's Next?
Ordered, mutable — great for sequences of changing data

→ List Comprehensions

Tuples
→ Nested Structures
Ordered, immutable — perfect for fixed data like coordinates

→ Sorting & Filtering


Dictionaries
→ File I/O with dicts
Key-value pairs — ideal for structured records & fast lookup

→ JSON & APIs


Sets
Unique elements — useful for removing duplicates & set math → Pandas DataFrames

Practice on [Link] · [Link] · [Link] · [Link]/python

You might also like