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

2 Python Data Structures

The document provides an overview of data structures in Python, including lists, tuples, dictionaries, and sets, along with their methods and use cases. It also covers functions, including their definitions, arguments, lambda functions, and scope. Additionally, it introduces comprehensions and built-in functional tools like map(), filter(), and zip(), along with practice exercises for hands-on learning.

Uploaded by

dola.mbstu
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 views5 pages

2 Python Data Structures

The document provides an overview of data structures in Python, including lists, tuples, dictionaries, and sets, along with their methods and use cases. It also covers functions, including their definitions, arguments, lambda functions, and scope. Additionally, it introduces comprehensions and built-in functional tools like map(), filter(), and zip(), along with practice exercises for hands-on learning.

Uploaded by

dola.mbstu
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

Part 2

Data Structures & Functions


Lists, Tuples, Dicts, Sets & Functions
1. Lists
Lists are ordered, mutable collections that can hold mixed data types. They are one of the most
frequently used data structures in Python.

fruits = ["apple", "banana", "cherry"]


[Link]("mango")
[Link]("banana")
print(fruits[0]) # apple
print(fruits[-1]) # mango
print(fruits[1:3]) # slicing
print(len(fruits)) # 3

Common List Methods


nums = [4, 1, 3, 2]
[Link]() # [1, 2, 3, 4]
[Link]() # [4, 3, 2, 1]
[Link](1, 99) # insert at index 1
[Link]() # removes & returns last item
[Link](99) # find index of value
print([Link](3)) # count occurrences

Nested Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # 6
for row in matrix:
print(row)

Copying Lists
Assigning a list to a new variable just creates another reference to the same list. Use .copy() or
slicing to make a real copy:

a = [1, 2, 3]
b = a # same list!
c = [Link]() # independent copy
d = a[:] # also a copy

2. Tuples
Tuples are like lists but immutable — once created, they cannot be changed. They are often used
for fixed collections of values, like coordinates.

point = (10, 20)


x, y = point # unpacking
print(x, y) # 10 20

single = (5,) # a one-element tuple needs a trailing comma


print(type(single)) # <class 'tuple'>
Why Use Tuples Instead of Lists?
• Immutability protects data from accidental modification

• Tuples can be used as dictionary keys, lists cannot

• Slightly faster and more memory-efficient than lists

3. Dictionaries
Dictionaries store key-value pairs and provide fast lookups. Since Python 3.7, dictionaries preserve
insertion order.

student = {"name": "Rafi", "age": 21, "dept": "CSE"}


print(student["name"]) # Rafi
student["age"] = 22
for key, value in [Link]():
print(key, "->", value)

Useful Dictionary Methods


print([Link]("gpa", "N/A")) # default if key missing
print([Link]())
print([Link]())
[Link]("dept")
[Link]({"gpa": 3.8})

Dictionary Comprehensions
squares = {x: x**2 for x in range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}

Nested Dictionaries
users = {
"u1": {"name": "Alice", "age": 25},
"u2": {"name": "Bob", "age": 30},
}
print(users["u1"]["name"]) # Alice

4. Sets
Sets store unique, unordered elements — useful for removing duplicates and performing
mathematical set operations.

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union {1,2,3,4,5}
print(a & b) # intersection {3}
print(a - b) # difference {1,2}
print(a ^ b) # symmetric difference {1,2,4,5}
Removing Duplicates with Sets
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums))
print(unique) # [1, 2, 3, 4]

5. Functions
Functions group reusable logic. They can take parameters and return values, which helps avoid
repeating code.

def greet(name, greeting="Hello"):


return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", "Hi"))

*args and **kwargs


def total(*nums):
return sum(nums)

print(total(1, 2, 3, 4)) # 10

def describe(**info):
for key, value in [Link]():
print(f"{key}: {value}")

describe(name="Alice", age=25)

Lambda Functions
Lambdas are small, anonymous, single-expression functions:

square = lambda x: x ** 2
print(square(5)) # 25

nums = [3, 1, 4, 1, 5]
print(sorted(nums, key=lambda x: -x)) # descending sort

Scope: Local vs Global


counter = 0

def increment():
global counter
counter += 1

increment()
print(counter) # 1
6. Comprehensions
Comprehensions are a concise way to build lists, dicts, and sets from existing iterables in a single
readable line.

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


evens = [x for x in range(20) if x % 2 == 0]
print(squares)
print(evens)

Nested Comprehensions
pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)
# [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]

7. Built-in Functional Tools


map(), filter(), and zip() are powerful tools for working with iterables without writing explicit loops.

nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

names = ["Alice", "Bob"]


ages = [25, 30]
paired = list(zip(names, ages))
print(doubled, evens, paired)

Practice Exercises
• Given a list of numbers, return only the even ones using a list comprehension.

• Write a function that counts word frequency in a sentence using a dictionary.

• Merge two lists into one without duplicate values.

• Write a function that returns the second-largest number in a list.

• Create a dictionary comprehension that maps each word in a sentence to its length.

• Use zip() to combine two lists into a dictionary.

• Write a lambda function that checks if a number is prime.

You might also like