Student Activity

Student Activity Guide:

1) Lists, Tuples, Sets, and Dictionaries

  • Create a list of numbers and print each number.

  • Convert the list into a tuple and try to modify an element (observe the error).

  • Create a set with duplicate values and print it to understand uniqueness.

  • Create a dictionary with name-age pairs and retrieve values by keys.

Example Code:

# Lists
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

# Tuples (Immutable)
numbers_tuple = tuple(numbers)
try:
    numbers_tuple[0] = 10  # This will raise an error
except TypeError as e:
    print(f"Error: {e}")

# Sets (Unique Values)
numbers_set = {1, 2, 2, 3, 4, 5}
print(numbers_set)  # Duplicates are removed

# Dictionaries
person = {"name": "Alice", "age": 25}
print(f"Name: {person['name']}, Age: {person['age']}")

2) Mutable vs Immutable Objects

  • Modify a list and a tuple to see the difference.

  • Create a function that modifies a mutable object and observe the changes.

Example Code:

def modify_list(lst):
    lst.append(100)
    print("Inside function:", lst)

nums = [1, 2, 3]
modify_list(nums)
print("Outside function:", nums)  # List changes persist

# Immutable Example with Strings
greeting = "Hello"
new_greeting = greeting.replace("H", "J")
print(greeting)  # Original string remains unchanged
print(new_greeting)

3) String Manipulation and Formatting

  • Concatenate strings using + and join.

  • Format strings using f-strings and .format().

  • Convert string cases (uppercase, lowercase, title case).

Example Code:

# String Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

# String Formatting
age = 30
formatted_string = f"My name is {full_name} and I am {age} years old."
print(formatted_string)

# Case Conversion
text = "hello world"
print(text.upper())  # HELLO WORLD
print(text.title())  # Hello World

4) List Comprehensions and Dictionary Comprehensions

  • Use list comprehensions to create a squared numbers list.

  • Create a dictionary from two lists using dictionary comprehension.

Example Code:

# List Comprehension
squared_numbers = [x**2 for x in range(10)]
print(squared_numbers)

# Dictionary Comprehension
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)

Student Exercises:

  1. Create a dictionary that stores student names and their scores. Retrieve and modify values.

  2. Write a function that accepts a list and returns a new list with squared values using list comprehension.

  3. Experiment with tuple unpacking and accessing values by index.

  4. Implement a function that converts a given sentence into title case and removes extra spaces.

Last updated