0% found this document useful (0 votes)
3 views14 pages

DataStructures Updated

This lecture covers Python data structures, specifically Lists, Tuples, and Dictionaries, focusing on their creation, manipulation, and appropriate use cases. It explains the characteristics of each structure, including mutability, ordering, and methods for adding, updating, and removing elements. The lecture also highlights practical applications of these data structures in real-world scenarios.
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)
3 views14 pages

DataStructures Updated

This lecture covers Python data structures, specifically Lists, Tuples, and Dictionaries, focusing on their creation, manipulation, and appropriate use cases. It explains the characteristics of each structure, including mutability, ordering, and methods for adding, updating, and removing elements. The lecture also highlights practical applications of these data structures in real-world scenarios.
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

6/6 /2 0 2 6

Lecture 13

Python Data Structures


Lists • Tuples • Dictionaries

Applications of ICT | University of Engineering & Technology, Taxila

Learning Objectives

• Understand what data structures are and why we use them


• Create and manipulate Python Lists (add, update, remove, sort)
• Work with Tuples — access, slice, unpack, and concatenate
• Build and query Dictionaries using key-value pairs
• Choose the right data structure for a given problem 1

Lecture 13 • Python Data Structures | 2 / 27

2
6/6 /2 0 2 6

What Are Data Structures?

A way to organize, store, and manage data in memory so it can be used efficiently.

• Without them: every value needs its own variable


• With them: group related data under one name
• Enables: iteration, search, update, and passing data to functions
• Python provides 4 built-in types: List, Tuple, Dictionary, Set

Structure Ordered? Mutable? Duplicates?

List Yes Yes Yes

Tuple Yes ✘ No Yes

Dictionary Yes Yes Keys: No

Lecture 13 • Python Data Structures | 3 / 27

List — Overview PART 1

• Ordered, mutable collection enclosed in square brackets [ ]


• Items can be of any data type and can repeat (duplicates allowed)
• Zero-based indexing: first element is at index 0
• Negative indexing: list[-1] returns the last element
• Supports slicing: list[1:4] returns elements at index 1, 2, 3
2
• List comprehension: [x**2 for x in range(5)] — one-line list creation

Lecture 13 • Python Data Structures | 4 / 27

4
6/6 /2 0 2 6

Creating a List

• Use square brackets [ ] with comma-separated values


• Items can be integers, strings, floats, booleans — even other lists
• Repeat elements using the * operator
r = [1, 2, 3]
print(r)

fruits = ["apple", "banana"]


print(fruits)
List1 = [4] * 3
print(List1) # Repeated elements

Output: [1, 2, 3]
['apple', 'banana']
[4, 4, 4]

Lecture 13 • Python Data Structures | 5 / 27

Accessing List Elements

• Posi ve index: a[0] → first, a[1] → second …


• Negative index: a[-1] → last, a[-2] → second-to-last
• Slicing: a[start:stop] — stop index is excluded

a = [10, 20, 30, 40, 50]


print(a[0]) # First element 3
print(a[-1]) # Last element
print(a[1:4]) # Slice: index 1,2,3

Output: 10
50
[20, 30, 40]

Lecture 13 • Python Data Structures | 6 / 27

6
6/6 /2 0 2 6

Adding Elements to a List

append() insert() extend()

Adds one element at the end Inserts at a specific index Adds multiple elements at end

a = [1,2] a = [1,3] a = [1,2]


[Link](3) [Link](1, 2) [Link]([3,4])
print(a) print(a) print(a)

→ [1, 2, 3] → [1, 2, 3] → [1, 2, 3, 4]

Lecture 13 • Python Data Structures | 7 / 27

Updating & Removing Elements

Updating (lists are mutable — assign by index):


a = [10, 20, 30, 40, 50]
a[1] = 25
print(a)

Output: [10, 25, 30, 40, 50]


4
Removing elements — four methods:

remove(val) Removes first occurrence of value

pop(index) Removes & returns element at index (default: last)

del a[index] Deletes element at index

clear() Empties the entire list

Lecture 13 • Python Data Structures | 8 / 27

8
6/6 /2 0 2 6

remove() and pop() — Examples

remove() — first occurrence pop() — by index / last

nums = [30, 15, 10, 20, 10, 40] a = [1,2,3]


[Link]() # removes last
[Link](10)
print(a)
print(nums)
→ [1, 2]
Output: [30, 15, 20, 10, 40]
a = [1,2,3]
[Link](0) # removes index 0
print(a)

→ [2, 3]

del and clear():

a = [2,4,7]; del a[1]; print(a) # [2, 7]


b = [4,5,9]; [Link](); print(b) # []

→ [2, 7] and []

Lecture 13 • Python Data Structures | 9 / 27

Sorting, Counting & Reversing

• count(val) — returns number of times a value appears


• sort() — sorts list in ascending order (in-place)
• reverse() — reverses the order of elements (in-place)
a = [30, 15, 20, 10, 40, 4, 4]

print([Link](4)) # Count occurrences of 4 5

[Link]()
print(a) # Ascending sort

[Link]()
print(a)2
Output: # Reversed order
[4, 4, 10, 15, 20, 30, 40]
[40, 30, 20, 15, 10, 4, 4]

Lecture 13 • Python Data Structures | 10 / 27

10
6/6 /2 0 2 6

Lists in the Real World

• Student marks: marks = [85, 72, 90, 68] → average, max, sort
• Shopping cart: cart = ['apple','milk','bread'] → add/remove items
• Sensor readings: temps = [36.5, 37.1, 38.0] → monitoring + alerts
• Queue simula on: tasks = [] → append() to enqueue, pop(0) to dequeue
• File lines: lines = open('[Link]').readlines() → each line is a list item

List Comprehension — one-liner power:

squares = [x**2 for x in range(1, 6)]


print(squares)

Output: [1, 4, 9, 16, 25] Lecture 13 • Python Data Structures | 11 / 27

11

Tuple — Overview PART 2

An immutable ordered collection — like a list that is locked after creation.

• Created with parentheses ( ) or just commas


• Ordered: elements maintain insertion order
• Immutable: cannot add, remove, or modify elements
• Allows duplicates and mixed data types 6

• Faster than lists — ideal for fixed data (coordinates, RGB colours, dates)

my_list = [1, 2, 3] # List — mutable


my_tuple = (1, 2, 3) # Tuple — immutable

my_list[0] = 99 # OK
# my_tuple[0] = 99 # ✘ TypeError

Lecture 13 • Python Data Structures | 12 / 27

12
6/6 /2 0 2 6

Creating Tuples

• Use parentheses with comma-separated values


• Convert a list to tuple with tuple( ) constructor
• Convert a string to tuple of characters with tuple('text')
• Mixed data types are allowed
# Empty tuple
t1 = ()

# String tuple
t2 = ('Geeks', 'For')
print(t2)

# From a list
t3 = tuple([1, 2, 4, 5, 6])
print(t3)
Output: ('Geeks', 'For')
(1, 2, 4, 5, 6)
(5, 'Welcome',
# Mixed 7.5, True, [1, 2, 3])
datatypes
t4 = (5, 'Welcome', 7.5, True,Lecture
[1,13 2, 3])
• Python Data Structures | 13 / 27
print(t4)
13

Accessing & Slicing Tuples

• Same indexing as lists: t[0] → first, t[-1] → last


• Slicing syntax: tuple[start : stop : step]
• Tuple unpacking: assign elements directly to variables
tup = tuple("PAKISTAN") # ('P','A','K','I','S','T','A','N')
print(tup[0]) # 'P'
print(tup[1:4]) # ('A','K','I') 7
print(tup[::-1]) # Reversed
print(tup[4:8]) # ('S','T','A','N')

# Tuple unpacking
univs = ("UET", "NUST", "GIKI")
a, b, c = univs
print(a, b, c)
Output: 'P'
('A', 'K', 'I')
('N', 'A', 'T', 'S', 'I', 'K', 'A', 'P')
('S', 'T', 'A', 'N')
UET NUST GIKI
Lecture 13 • Python Data Structures | 14 / 27

14
6/6 /2 0 2 6

Concatenation & Asterisk Unpacking

Concatenation with + Asterisk * Unpacking

Only tuples can be joined — mixing with a list raises TypeError Grabs multiple middle items into a list

t1 = (0, 1, 2, 3) tup = (1, 2, 3, 4, 5)


t2 = ('the', 'quick', 'brown') a, *b, c = tup
t3 = t1 + t2 print(a) # 1
print(t3) print(b) # [2, 3, 4]
print(c) # 5
Output: (0,1,2,3,'the','quick','brown')
Output: 1
[2, 3, 4]
5
Dele ng a Tuple (immutable → only del en re tuple):

tup = (1, 2, 3)
del tup # Deletes the whole tuple
# print(tup) # NameError — no longer exists
Lecture 13 • Python Data Structures | 15 / 27

15

List vs Tuple — When to Use Which?

Feature List Tuple

Syntax [] ()

Mutability Mutable Immutable ✘

8
Speed Slightly slower Faster

Use when… Data will change Data is fixed

Examples Cart, scores, logs GPS, RGB, config

Dict key? No (unhashable) Yes (hashable)

Lecture 13 • Python Data Structures | 16 / 27

16
6/6 /2 0 2 6

Dictionary — Overview PART 3

Stores data as key : value pairs — like a real-world dictionary.

• Each key is unique — reusing a key overwrites its value


• Keys are case-sensitive: 'Name' ≠ 'name'
• Mutable: keys/values can be added, changed, or deleted
• Ordered (Python 3.7+): insertion order is preserved
• Values accessed via key: d['name'] or [Link]('name')

d = {"name": "Ali", "age": 21} # using { }


b = dict(name="Ahmad", age=20) # using dict()
print(d)
print(b)

Output: {'name': 'Ali', 'age': 21}


{'name': 'Ahmad', 'age': 20}
Lecture 13 • Python Data Structures | 17 / 27

17

Accessing Dictionary Items

• Square bracket notation: d['key'] — raises KeyError if missing


• get() method: [Link]('key') — returns None if key not found (safe)
• keys() — returns all keys; values() — returns all values
• items() — returns all key-value pairs as tuples
d = {"name": "Ali", "age": 21, "dept": "Civil"}
9
print(d["name"]) # 'Ali'
print([Link]("age")) # 21
print([Link]("gpa", 0.0)) # 0.0 (default if missing)

print([Link]()) # dict_keys(['name','age','dept'])
print([Link]()) # dict_values(['Ali', 21, 'Civil'])
print([Link]()) # dict_items([('name','Ali'), ...])
Output: 'Ali'
21
0.0
Lecture 13 • Python Data Structures | 18 / 27
dict_keys(['name', 'age', 'dept'])
18
6/6 /2 0 2 6

Adding & Updating Dictionary Items

• New key → assignment adds a new key-value pair


• Exis ng key → assignment overwrites the old value
• update() method — merges another dict or keyword arguments
d = {"name": "Muhammad"}

d["age"] = 21 # New key added


d["name"] = "Bilal" # Existing key updated
print(d) # {'name': 'Bilal', 'age': 21}

[Link]({"dept": "Civil", "age": 22})


print(d) # {'name':'Bilal','age':22,'dept':'Civil'}

Output: {'name': 'Bilal', 'age': 21}


{'name': 'Bilal', 'age': 22, 'dept': 'Civil'}

Lecture 13 • Python Data Structures | 19 / 27

19

Removing Dictionary Items

del d['key'] Removes item by key

[Link]('key') Removes & returns value for key

[Link]() Removes & returns last inserted pair

[Link]() Empties the dictionary

d = {"a": 1, "b": 2, "c": 3} 10

del d["a"] # {'b':2,'c':3}


val = [Link]("b") # val=2, d={'c':3}
print(val)

d2 = {"x": 10, "y": 20}


print([Link]()) # ('y', 20) last pair

[Link]()
Output: 2
('y', 20)
print(d2) # {}
{}
Lecture 13 • Python Data Structures | 20 / 27

20
6/6 /2 0 2 6

Iterating Over a Dictionary

• for k in d — iterates over keys


• for v in [Link]() — iterates over values
• for k, v in [Link]() — iterates over key-value pairs (most useful)
student = {"name": "Usman", "marks": 88, "grade": "A"}

# Keys only
for k in student:
print(k)

# Key-value pairs
for k, v in [Link]():
print(f"{k} : {v}")
Output: name
marks
grade
---
name : Usman
marks : 88 Lecture 13 • Python Data Structures | 21 / 27
grade : A
21

Dictionaries in the Real World

• Student database: {'roll': '19-CE-01', 'name': 'Ali', 'gpa': 3.7}


• JSON APIs: every web API response is a Python dictionary
• Word frequency counter: count how many times each word appears
• Phone book: {'Ahmad': '0300-1234567', 'Sara': '0321-9876543'}
• Configuration file: {'theme': 'dark', 'font_size': 14, 'lang': 'en'}
11

# Word frequency counter


sentence = "to be or not to be"
freq = {}
for word in [Link]():
freq[word] = [Link](word, 0) + 1
print(freq)

Output: {'to': 2, 'be': 2, 'or': 1, 'not': 1}


Lecture 13 • Python Data Structures | 22 / 27

22
6/6 /2 0 2 6

Choosing the Right Data Structure

Scenario Best Choice Why?

Student marks that need updating List Mutable, ordered

GPS coordinates (lat, lon) Tuple Immutable, fast

Map word → count Dictionary Key-value lookup

Months of the year (fixed order) Tuple Read-only sequence

Shopping cart items List Add/remove freely

User profile (name, age, email, …) Dictionary Named fields

Return two values from a function Tuple Lightweight pair

Lecture 13 • Python Data Structures | 23 / 27

23

Quick Practice Problems

Q1. Create a list of 5 cities. Add a new city, remove the first one, then sort the list.

Q2. Store your name, age, and CGPA in a tuple. Unpack and print each value on a separate line.

12
Q3. Build a dictionary for a student with keys: name, roll_no, marks. Update the marks to 95 and print.

Q4. Given nums = [4, 7, 2, 9, 4, 1, 4] — find how many times 4 appears, then sort ascending.

Q5. Create a dictionary from two lists: keys = ['a','b','c'] and vals = [1,2,3] using zip().

Lecture 13 • Python Data Structures | 24 / 27

24
6/6 /2 0 2 6

Nested Structures — Brief Intro

• Lists, tuples, and dicts can contain each other


• List of dicts: common for database-style records
• Dict of lists: group multiple values under one key
• Access nested items by chaining indices/keys
# List of student dictionaries
students = [
{"name": "Ali", "marks": 85},
{"name": "Sara", "marks": 92},
]
for s in students:
print(s["name"], "scored", s["marks"])

# Dict of lists
courses = {"CE": ["Maths","Physics"], "CS": ["Python","DS"]}
print(courses["CS"][1]) # 'DS'
Output: Ali scored 85
Sara scored 92
DS Lecture 13 • Python Data Structures | 25 / 27

25

Common Errors & How to Fix Them

IndexError: list index out of range

Check list length with len() before accessing an index

TypeError: 'tuple' object does not support item assignment

You're trying to modify a tuple — use a list if data must change


13

KeyError: 'name'

Key not found — use [Link]('name') or check 'name' in d first

ValueError: [Link](x): x not in list

Check if value exists before calling remove(): if x in lst: [Link](x)

Lecture 13 • Python Data Structures | 26 / 27

26
6/6 /2 0 2 6

Summary & Key Takeaways

List [ ] Ordered, mutable — add, remove, sort, iterate

Tuple ( ) Ordered, immutable — fast, safe, unpackable

Dictionary { } Key-value pairs — labelled, searchable, mutable

Right choice List if data changes | Tuple if fixed | Dict if labelled

Common ops append/pop/sort for list; get/update/del for dict

Next: Sets & String Methods | Practice: Complete the assessment problems

27

14

You might also like