0% found this document useful (0 votes)
4 views

Python Day 9

Uploaded by

dalveer0302
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)
4 views

Python Day 9

Uploaded by

dalveer0302
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
You are on page 1/ 17

Python Day- 9

(RECAP OF PREVIOUS DAY)

Sequences: Packing and unpacking, Mutable vs. immutable sequences, Strings: Advanced
methods, Lists and list comprehensions, Tuples , Problems on above concepts.

Sequences in Python

Sequences are ordered collections of items. Python provides several built-in sequence
types, including:

●​ Strings
●​ Lists
●​ Tuples

All sequences share common operations, such as indexing, slicing, and iterating.

Packing and Unpacking

Packing

Packing means assigning multiple values to a single variable.

# Packing example

packed = 1, 2, 3, 4

print(packed) # Output: (1, 2, 3, 4)

Unpacking
Unpacking allows you to assign elements of a sequence to multiple variables.

# Unpacking example

x, y, z = 10, 20, 30

print(x, y, z) # Output: 10 20 30

# Using * to collect remaining items

*a, b = [1, 2, 3, 4]

print(a, b) # Output: [1, 2, 3] 4

Key Notes:

●​ Number of variables on the left must match the elements unless * is used.
●​ Useful in returning multiple values from a function.

Example with a function:

def return_multiple():

return 5, 10, 15

val1, val2, val3 = return_multiple()

print(val1, val2, val3) # Output: 5 10 15


Mutable vs. Immutable Sequences

Mutable Sequences

Mutable sequences can be modified after creation. You can change its value.

●​ Example: Lists

my_list = [1, 2, 3]

my_list[1] = 20 # Modifying element

print(my_list) # Output: [1, 20, 3]

Immutable Sequences

Immutable sequences cannot be changed once created.

●​ Examples: Strings and Tuples

# Strings

text = "hello"

# text[0] = "H" # This will raise an error

text = "Hello" # Reassignment is allowed

# Tuples

my_tuple = (1, 2, 3)

# my_tuple[0] = 10 # This will raise an error


Comparison of Mutable and Immutable Sequences:

Property Mutable (Lists) Immutable (Strings, Tuples)

Modifiable? Yes No

Performance Slower (more overhead) Faster (fixed structure)

Use Case When frequent updates are For read-only or fixed data
needed

Strings: Advanced Methods

Strings in Python are immutable sequences of characters. Here are some advanced
methods:

Useful String Methods

Method Description Example

capitalize() Converts the first character "hello".capitalize() → "Hello"


to uppercase.
casefold() Converts the string to "HELLO".casefold() → "hello"
lowercase (more
aggressive than lower()).

lower() Converts all characters to "HELLO".lower() → "hello"


lowercase.

upper() Converts all characters to "hello".upper() → "HELLO"


uppercase.

title() Converts the first character "hello world".title() → "Hello World"


of each word to
uppercase.

swapcase() Swaps case of all "Hello".swapcase() → "hELLO"


characters.

find(substring) Returns the index of the "hello".find("e") → 1


first occurrence of the
substring, or -1 if not
found.

rfind(substring) Returns the index of the "hello".rfind("l") → 3


last occurrence of the
substring, or -1 if not
found.
index(substring Like find(), but raises a "hello".index("e") → 1
) ValueError if the substring
is not found.

count(substring Counts occurrences of the "hello world".count("l") → 3


) substring.

replace(old, Replaces all occurrences "hello".replace("l", "x") → "hexxo"


new) of old with new.

split(delimiter) Splits the string into a list "a,b,c".split(",") → ["a", "b", "c"]
using delimiter.

rsplit(delimiter) Splits from the right side. "a,b,c".rsplit(",", 1) → ["a,b", "c"]

splitlines() Splits the string at line "Hello\nWorld".splitlines() → ["Hello",


breaks. "World"]

strip() Removes leading and " hello ".strip() → "hello"


trailing whitespace (or
specified characters).

lstrip() Removes leading " hello".lstrip() → "hello"


whitespace (or specified
characters).
rstrip() Removes trailing "hello ".rstrip() → "hello"
whitespace (or specified
characters).

startswith(subst Returns True if the string "hello".startswith("he") → True


ring) starts with the given
substring.

endswith(substr Returns True if the string "hello".endswith("lo") → True


ing) ends with the given
substring.

join(iterable) Joins elements of an ",".join(["a", "b", "c"]) → "a,b,c"


iterable with the string as a
separator.

isalpha() Returns True if all "abc".isalpha() → True,


characters are alphabetic. "abc123".isalpha() → False

isdigit() Returns True if all "123".isdigit() → True,


characters are digits. "123abc".isdigit() → False

isalnum() Returns True if all "abc123".isalnum() → True, "abc


characters are 123".isalnum() → False
alphanumeric (letters or
digits).
isspace() Returns True if all " ".isspace() → True,
characters are whitespace.
" a ".isspace() → False

len() Returns the length of the len("hello") → 5


string.

format() Formats the string using "Hello, {}".format("World") → "Hello,


placeholders {}. World"

zfill(width) Pads the string with zeroes "42".zfill(5) → "00042"


on the left until the
specified width is reached.

center(width) Centers the string in a field "hello".center(10) → " hello "


of specified width.

ljust(width) Left-justifies the string in a "hello".ljust(10) → "hello "


field of specified width.

rjust(width) Right-justifies the string in "hello".rjust(10) → " hello"


a field of specified width.

String Formatting

●​ f-strings:

name = "Alice"
age = 25

print(f"Name: {name}, Age: {age}") # Output: Name: Alice, Age: 25

Lists and List Comprehensions

Lists

Lists are mutable sequences that can hold mixed data types.

List Methods:

Method Description Example

append(x) Adds an element x to lst = [1, 2];


the end of the list. lst.append(3) → [1, 2, 3]

extend(iterable) Extends the list by lst = [1, 2];


appending all elements lst.extend([3, 4]) → [1,
from the given iterable.
2, 3, 4]

insert(i, x) Inserts an element x at lst = [1, 2];


position i. lst.insert(1, 99) → [1,
99, 2]
remove(x) Removes the first lst = [1, 2, 3];
occurrence of element lst.remove(2) → [1, 3]
x.

pop([i]) Removes and returns lst = [1, 2, 3];


the element at position lst.pop(1) → Returns 2, list
i (last if i is not
becomes [1, 3]
provided).

clear() Removes all elements lst = [1, 2, 3];


from the list. lst.clear() → []

index(x, [start, Returns the index of the lst = [1, 2, 3];


end]) first occurrence of x in lst.index(2) → 1
the list.

count(x) Returns the number of lst = [1, 2, 2, 3];


occurrences of x in the lst.count(2) → 2
list.

sort(key=None, Sorts the list in lst = [3, 1, 2];


reverse=False) ascending order (or lst.sort() → [1, 2, 3]
based on a key
function).
reverse() Reverses the elements lst = [1, 2, 3];
of the list in place. lst.reverse() → [3, 2, 1]

copy() Returns a shallow copy lst = [1, 2];


of the list.
new_lst = lst.copy() →
new_lst = [1, 2]

List Comprehensions

List comprehensions provide a concise(short) way to create lists.

Syntax:

[expression for item in iterable if condition]

Examples:

# Create a list of squares

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

print(squares) # Output: [1, 4, 9, 16, 25]


# Filter even numbers

evens = [x for x in range(10) if x % 2 == 0]

print(evens) # Output: [0, 2, 4, 6, 8]

Tuples

Tuples are immutable sequences, often used for fixed collections of items.

Tuple Methods

●​ tuple.count(value): Counts the number of occurrences of a value.


●​ tuple.index(value): Finds the first index of a value.

Examples:

my_tuple = (10, 20, 30, 10)

print(my_tuple.count(10)) # Output: 2

print(my_tuple.index(20)) # Output: 1

Tuple Packing and Unpacking


# Packing

packed = 1, 2, 3

# Unpacking

x, y, z = packed

print(x, y, z) # Output: 1 2 3

Problems and Exercises

Problem 1: Packing and Unpacking

Write a function that returns the sum and product of two numbers. Use unpacking to
assign the results.

def sum_and_product(a, b):

return a + b, a * b

result_sum, result_product = sum_and_product(4, 5)

print(result_sum, result_product) # Output: 9 20

Problem 2: Filtering with List Comprehensions

Create a list of squares for all odd numbers between 1 and 10.
odd_squares = [x**2 for x in range(1, 11) if x % 2 != 0]

print(odd_squares) # Output: [1, 9, 25, 49, 81]

Problem 3: Tuple Manipulation

Given a tuple (10, 20, 30, 40), write a function to:

1.​ Count occurrences of 20.


2.​ Find the index of 30.

my_tuple = (10, 20, 30, 40)

print(my_tuple.count(20)) # Output: 1

print(my_tuple.index(30)) # Output: 2

Problem 4: Advanced Strings

Write a program to count the number of vowels in a given string.

text = "Hello, Python!"

vowels = [char for char in text.lower() if char in "aeiou"]

print(len(vowels)) # Output: 3

Problem 5: Mutable vs. Immutable

What happens if you try to modify a tuple? Test this with code.
my_tuple = (1, 2, 3)

# my_tuple[0] = 10 # Uncommenting this will raise a TypeError

_____________________________________________

Programs to practice (HW)​

1. Sequences: Packing and Unpacking

1.​ Write a program to demonstrate tuple packing and unpacking with multiple
variables.
2.​ Write a program to swap two variables using tuple unpacking.
3.​ Create a function that returns multiple values (e.g., sum and product of two
numbers) and unpack them in the caller.
4.​ Write a program to unpack a nested list or tuple and access its inner elements.
5.​ Demonstrate how to unpack sequences with * (e.g., head, *middle, tail).

2. Mutable vs. Immutable Sequences

6.​ Write a program to show the difference between mutable (list) and immutable
(tuple) sequences by modifying elements.
7.​ Create a program to compare memory addresses of mutable vs immutable
sequences when their values are changed.
8.​ Write a program to simulate a shopping cart using a list (mutable) and a tuple
(immutable).
9.​ Demonstrate how slicing works differently in mutable and immutable sequences.
10.​Show how concatenation affects both mutable and immutable sequences.

3. Strings: Advanced Methods

11.​Write a program to demonstrate the use of join(), split(), strip(),


find(), and replace() methods.
12.​Create a program to count the frequency of each word in a given sentence.
13.​Write a program to capitalize the first letter of every word in a string and reverse
the case of all other letters.
14.​Develop a function to find all palindromic substrings in a given string.
15.​Implement a program to extract email addresses or URLs from a given text using
string methods.

4. Lists and List Comprehensions

16.​Write a program to generate a list of squares for numbers from 1 to 10 using list
comprehensions.
17.​Create a list comprehension to filter out vowels from a given string.
18.​Write a program to flatten a 2D list (list of lists) into a single list using list
comprehensions.
19.​Generate a list of all prime numbers between 1 and 50 using list
comprehensions.
20.​Write a program to create a dictionary from two lists using list comprehensions.

5. Tuples

21.​Write a program to create a tuple, access its elements, and demonstrate its
immutability.
22.​Develop a program to sort a list of tuples based on the second element of each
tuple.
23.​Write a program to find the maximum and minimum elements in a tuple of
numbers.
24.​Create a program to demonstrate the use of tuples as keys in a dictionary.
25.​Write a program to find the index of a given element in a tuple.

6. Problems Combining the Above Concepts

26.​Write a program to combine two lists into a list of tuples using zip(), and then
unpack the tuples.
27.​Develop a function that takes a list of integers and returns a tuple with the even
numbers in one list and odd numbers in another.
28.​Write a program to demonstrate the difference between shallow and deep copies
of a list containing tuples.
29.​Create a function that takes a string of numbers separated by commas, converts
it to a list of integers, and returns their sum.
30.​Develop a program to convert a list of strings to uppercase and remove
duplicates using list comprehensions.

You might also like