Unit Iii
Unit Iii
Lists in
Python
List
• In Python, a list is a widely used data structure that allows you to store
multiple items in a single variable.
structures:
first select a sublist (row) and then an element within that sublist (column).
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
Iterating Over Lists
• You can loop through lists using for loops:
• What Is a Sequence?
A sequence in Python is an iterable data structure that maintains the order of its elements. This means
you can access elements by their position (index) in the sequence. Common sequence types include:
• Tuples: Immutable sequences, meaning their elements cannot be changed after creation.
• In Python, lists are mutable, meaning you can change their content after
creation without altering their identity. This includes modifying elements,
adding new items, or removing existing ones.
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list)
# Output: [10, 2, 3]
Adding Elements
• Using append(): Adds a single element to the end of the list.
my_list.append(4)
print(my_list)
# Output: [10, 2, 3, 4]
Removing Elements
• Using remove(): Removes the first occurrence of a specified value.
my_list.remove(2)
print(my_list)
# Output: [10, 3, 4, 5, 6]
Mutable vs. Immutable Types in
Python
Mutable Types Immutable Types
list int, float
dict str
set tuple
Custom class frozenset
objects
Traversing a List
• Traversing a list in Python means accessing each element in the list,
one by one, to perform operations such as printing, modifying, or
applying functions
• This method is ideal when you need to read or process each item in
the list.
2. Using for Loop with range()
and len()
• When you need to access both the index and the value, combining
range() with len() is effective:
This approach is suitable for simple operations and can make the code
more readable.
6. Traversing Nested Lists
• For lists containing sublists, nested loops are necessary:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=' ‘)
This method allows you to access each element within the nested lists.
7. Using zip() to Traverse
Multiple Lists
• When you need to traverse multiple lists simultaneously, zip() is
useful:
• Adding Elements
• Removing Elements
• Searching and Counting
• Sorting and Reversing
• Copying and Slicing
List slices
• In Python, list slicing is a powerful technique that allows you to access
a subset of elements from a list. The general syntax for slicing is:
• list[start:stop:step]
Basic Slicing Examples
• Given the list:
numbers[:3]
• The map() function applies the given function to each item of the
iterable(s) and returns a map object. To obtain a list of the results, you
can convert the map object using list()
Examples
• 1. Using map() with a Built-in Function
numbers = [1, 2, 3, 4]
squared = map(pow, numbers, numbers) # Equivalent to [1^1, 2^2,
3^3, 4^4]
print(list(squared))
# Output: [1, 4, 27, 256]
2. Using map() with a User-
defined Function
def square(n):
return n * n
numbers = [1, 2, 3, 4]
squared = map(square, numbers)
print(list(squared)) # Output: [1, 4, 9, 16]
3. Using map() with a Lambda
Function
numbers = [1, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))
• When working with large datasets where lazy evaluation can improve
performance.
Filter and reduce
• In Python, the filter() and reduce() functions are powerful tools for
processing iterables.
• Here's an overview of each:
• filter() – Selecting Elements Based on a Condition
• Purpose: The filter() function constructs an iterator from elements of
an iterable for which a function returns True.
• filter(function, iterable)
Example: Filtering even
numbers from a list.
• numbers = [1, 2, 3, 4, 5, 6]
• even_numbers = filter(lambda x: x % 2 == 0, numbers)
• print(list(even_numbers))
• # Output: [2, 4, 6]
reduce() – Aggregating
Elements into a Single Value
• Purpose: The reduce() function applies a specified function
cumulatively to the items of an iterable, reducing the iterable to a
single accumulated value.
• Note: In Python 3, reduce() is available in the functools module and
needs to be imported.
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result) # Output: 15
Key Differences
Function Type Function that returns True or False Function that combines two values
# Deleting a slice
del colors[1:3]
print(colors)
# Output: ['red']
4. clear() – Remove All Elements
• The clear() method removes all items from the list, resulting in an
empty list.
items = [1, 2, 3]
items.clear()
print(items)
# Output: []
5. List Comprehension – Remove
Elements Conditionally
• List comprehensions can create a new list excluding elements that
meet certain conditions.
numbers = [1, 2, 3, 4, 5]
filtered = [num for num in numbers if num % 2 == 0]
print(filtered) # Output: [2, 4]
6. Removing Multiple Elements
• To remove multiple specific elements, you can use a loop or list
comprehension:
• Here, a and b are two distinct list objects (different identities) but have the
same value.
• You can check:
• Equality of values: a == b returns True because their contents are the same.
• Identity: a is b returns False because they are different objects in memory.
Key Differences
x = "hello"
y=x
y = "world"
print(x)
# Output: "hello"
Checking for Aliasing
• You can check if two variables are aliases (i.e., refer to the same
object) using the is operator:
a = [1, 2, 3]
b=a
print(a is b)
# Output: True
Function Aliasing
• Aliasing can also apply to functions. Assigning a function to another
variable creates an alias:
def greet():
print("Hello!")
say_hello = greet
say_hello()
# Output: Hello!
List arguments
• In Python, passing a list as an argument to a function allows the
function to access and manipulate the list's elements.
• Since lists are mutable, any changes made to the list within the
function will affect the original list outside the function.
Basic Example: Passing a List to
a Function
def print_list(a):
for item in a:
print(item)
• apple
• banana
• cherry
Modifying the Original List
• Since lists are mutable, modifications within the function will affect
the original list.
def add_item(items, new_item):
items.append(new_item)
a = [1, 2, 3]
add_item(a, 4)
print(a)
[1, 2, 3, 4]
Using *args to Unpack a List
into Separate Arguments
• If you want to pass a list where each element is treated as a separate
argument, you can use the unpacking operator *
• 1. From an Iterable
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
word_counts = Counter(words)
print(word_counts)
# Output: Counter({'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1,
'over': 1, 'lazy': 1, 'dog': 1})
Looping and dictionaries
• Looping through dictionaries in Python is a fundamental skill, allowing
you to access and manipulate keys, values, or both.
• Here's a comprehensive guide on various methods to iterate over
dictionaries:
# output;
1
2
3
Looping Through Key-Value
Pairs
• To access both keys and values simultaneously, use the .items()
method:
print(inverted_dict[2])
# Output: 'b'
3. Finding All Keys for a Given
Value
• To find all keys that map to a specific value:
Syntax [] {}
• List Example:
• pythonCopyEditfruits = ['apple', 'banana', 'cherry’]
• print(fruits[1])
• # Output: banana
• Dictionaries Example:
• person = {'name': 'Alice', 'age': 30}
• print(person['name'])
• # Output: Alice
Memos
1.If not: Compute the result, store it in the cache, and then return it.
factorial_memo = {}
def factorial(n):
if n < 2:
return 1
if n not in factorial_memo:
factorial_memo[n] = n * factorial(n - 1)
return factorial_memo[n]
2. Using functools.lru_cache
Decorator
• Python's functools module provides the lru_cache decorator, which simplifies
memoization:
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Global variables
def myfunc():
print("Python is " + x)
myfunc()
print("Outside function:", x)
#Output:Python is awesome
Outside function: awesome
Modifying Global Variables
Inside Functions
• By default, if you assign a value to a variable inside a function, Python treats it
as a local variable.
• To modify a global variable within a function, you must use the global
keyword.
x = 5 # Global variable
def myfunc():
global x
x = x + 1 # Modifies the global variable
myfunc()
Tuples: Tuples are immutable
• Tuples are immutable, meaning once created, their elements cannot
be changed, added, or removed.
# Example of a tuple
my_tuple = (1, 2, 3)
• Tuples are often used for fixed collections of items (like coordinates,
RGB colors, etc.).
• If you need a collection where you might need to modify the contents
later, use a list instead of a tuple.
1. Creating and Accessing Tuple
# Creating a tuple
fruits = ("apple", "banana", "cherry")
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
2. Trying to Modify a Tuple
(Shows Error)
# Tuples are immutable
numbers = (1, 2, 3, 4)
# Unpacking
name, age, profession = person
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
2. Tuple Assignment Without
Parentheses
• You can even skip the parentheses:
x, y = 10, 20
print(x) # Output: 10
print(y) # Output: 20
3. Swapping Two Variables
(Using Tuple Assignment)
# Swapping values without a temporary variable
m, n = 5, 10
m, n = n, m
print(m) # Output: 10
print(n) # Output: 5
4. Nested Tuple Assignment
# Nested tuples
(person, (city, country)) = ("Alice", ("Paris", "France"))
Output:
Number 1 is written as one
Number 2 is written as two
Number 3 is written as three
Tuples as return values
• In Python, functions can return tuples, which is a convenient way to return
multiple values from a function.
• def min_max(numbers):
• minimum = min(numbers)
• maximum = max(numbers)
• return minimum, maximum # Returns a tuple
# Unpack
x_pos, y_pos = get_coordinates()
print("X:", x_pos) # Output: 10
print("Y:", y_pos) # Output: 20
Why Use Tuples for Return
Values?
• Clean way to return multiple pieces of related data.
• Easy to unpack and Use.
• Helps avoid returning custom objects or multiple return statements.
Variable-length argument tuples
• In Python, you can define a function to accept any number of
positional arguments using *args.
• Here, args is a tuple that collects all the extra positional arguments
passed to the function.
• Syntax:
def function_name(*args):
# args is a tuple
Example 1: Sum of Any Number
of Arguments
def total_sum(*args):
return sum(args)
apple
banana
cherry
Lists and tuples
Feature List Tuple
Syntax my_list = [1, 2, 3] my_tuple = (1, 2, 3)
Mutable? Yes (can change) No (immutable)
Many methods
Methods available Fewer methods like .count(), .index()
like .append(), .remove()
Can be used as dict keys? No (mutable) Yes (if all elements are immutable)
When to Use What?
• Use lists when:
• You need to modify, add, or remove elements.
• Order matters and may change.
• Use tuples when:
• You want a fixed collection of items.
• You need to ensure data integrity.
• You want to use the values as dictionary keys or in sets.
Dictionaries and tuples.
Feature Dictionary (dict) Tuple (tuple)
Mutable? Yes No
location_dict = {
(40.7128, -74.0060): "New York",
(34.0522, -118.2437): "Los Angeles"
}