Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! 🚀 Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
Converting Between Lists and Tuples
You can convert a list to a tuple and vice versa using list() and tuple() functions.

Examples:
# List to Tuple
list1 = [1, 2, 3]
tuple1 = tuple(list1)
print(tuple1) # Output: (1, 2, 3)

# Tuple to List
tuple2 = (4, 5, 6)
list2 = list(tuple2)
print(list2) # Output: [4, 5, 6]
Unpacking Lists and Tuples
You can "unpack" a list or tuple into individual variables.

Example:
point = (1, 2, 3)
x, y, z = point
print(x, y, z) # Output: 1 2 3
Practice Exercises for Day 6

Exercise 1: List Operations

Create a list of 5 numbers. Perform the following operations: append a new number, remove the second element, and sort the list.


Exercise 2: Find the Largest Number in a List
Write a Python program that finds the largest number in a list without using built-in functions.


Exercise 3: Tuple Packing and Unpacking
Write a Python program that packs four values into a tuple and then unpacks them into separate variables.


Exercise 4: List Comprehensions
Write a Python program that creates a new list with the squares of numbers from 1 to 10 using list comprehensions.


Exercise 5: Matrix Operations
Create a 3x3 matrix using nested lists. Write a Python program to print the matrix and its transpose.
Homework for Day 6

Create a Shopping Cart Program:

Create a Python program that allows the user to add items to a shopping cart. Use a list to store the items, and provide options to add, remove, view, and clear the cart.


Tuple-Based Menu:
Write a program that displays a tuple-based menu to the user. The menu should contain options for various operations (e.g., add, delete, view items) and perform actions based on user input.


Flatten a Nested List:
Write a Python program to flatten a nested list using list comprehensions.


Unique Elements Finder:
Create a Python program that takes a list of numbers and returns a new list containing only the unique elements (removing duplicates).


Tuple Manipulation:
Write a Python program to take a tuple of numbers and return a tuple containing only even numbers.
Summary
Today, we covered two of Python's fundamental data structures: Lists and Tuples. We learned:

Lists are mutable and allow for dynamic operations like adding, removing, and sorting elements.
Tuples are immutable, making them suitable for fixed collections of items.
List methods help manipulate lists efficiently.
Tuple methods provide limited but useful operations for tuple manipulation.
List comprehensions offer a concise way to create new lists.
Nested lists and unpacking are useful techniques for handling complex data.

These data structures are foundational for Python programming, and mastering them will help you manage and manipulate data effectively in your projects. Keep practicing and experimenting with these concepts to strengthen your Python skills. Happy coding!
ask your doubts at @kidscoderchat
What will be the output of the following code? for i in range(3):
print(i)
Anonymous Quiz
27%
1 2 3
67%
0 1 2
7%
0 1 2 3
0%
3 2 1
Introduction to Dictionaries
A dictionary in Python is an unordered collection of data in a key-value pair format. Unlike lists and tuples, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be of any immutable type (e.g., strings, numbers, tuples)

Syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
...
}

Example:
student = {
"name": "John",
"age": 21,
"courses": ["Math", "Physics"]
}
print(student) # Output: {'name': 'John', 'age': 21, 'courses': ['Math', 'Physics']}
Accessing Dictionary Elements
You can access dictionary values by using their corresponding keys.

Example:
print(student["name"])  # Output: John
print(student["courses"]) # Output: ['Math', 'Physics']

To avoid KeyError when accessing keys that may not exist, you can use the get() method, which returns None or a default value if the key is not found.

Example:
print(student.get("age"))  # Output: 21
print(student.get("grade", "Not Found")) # Output: Not Found
Adding and Modifying Dictionary Elements
You can add new key-value pairs or update existing ones using the assignment operator.


Example:
student["grade"] = "A"  # Adding a new key-value pair
print(student) # Output: {'name': 'John', 'age': 21, 'courses': ['Math', 'Physics'], 'grade': 'A'}

student["age"] = 22 # Modifying an existing key-value pair
print(student) # Output: {'name': 'John', 'age': 22, 'courses': ['Math', 'Physics'], 'grade': 'A'}
👍2
Removing Elements from a Dictionary
Dictionaries provide several methods for removing elements:

pop(key): Removes the item with the specified key and returns its value.
popitem(): Removes and returns the last inserted key-value pair.
del keyword: Deletes a specific key-value pair or the entire dictionary.
clear(): Removes all elements from the dictionary.
Example:
# Using pop()
age = student.pop("age")
print(age) # Output: 22
print(student) # Output: {'name': 'John', 'courses': ['Math', 'Physics'], 'grade': 'A'}

# Using popitem()
last_item = student.popitem()
print(last_item) # Output: ('grade', 'A')
print(student) # Output: {'name': 'John', 'courses': ['Math', 'Physics']}

# Using del
del student["courses"]
print(student) # Output: {'name': 'John'}

# Using clear()
student.clear()
print(student) # Output: {}
Looping through Dictionaries
You can loop through keys, values, or both in a dictionary.


Examples:
student = {
"name": "John",
"age": 21,
"courses": ["Math", "Physics"]
}

# Loop through keys
for key in student:
print(key)

# Loop through values
for value in student.values():
print(value)

# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
Dictionary Methods
Some useful dictionary methods:

keys(): Returns a list of all keys.
values(): Returns a list of all values.
items(): Returns a list of key-value pairs.
update(): Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.
Examples:
print(student.keys())    # Output: dict_keys(['name', 'age', 'courses'])
print(student.values()) # Output: dict_values(['John', 21, ['Math', 'Physics']])
print(student.items()) # Output: dict_items([('name', 'John'), ('age', 21), ('courses', ['Math', 'Physics'])])

# Using update()
student.update({"name": "Jane", "age": 22})
print(student) # Output: {'name': 'Jane', 'age': 22, 'courses': ['Math', 'Physics']}
Introduction to Sets
A set is an unordered collection of unique elements. Sets are mutable, but their elements must be immutable (e.g., strings, numbers, tuples). Sets do not allow duplicate values.

Syntax:
my_set = {element1, element2, element3, ...}

Example:
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Set Operations
Sets are useful for mathematical operations like union, intersection, difference, and symmetric difference.

union(): Returns a set containing all unique elements from both sets.
intersection(): Returns a set containing only the common elements.
difference(): Returns a set containing elements that are only in the first set.
symmetric_difference(): Returns a set containing elements in either set but not both.
Examples:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1.union(set2)) # Output: {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)) # Output: {3, 4}
print(set1.difference(set2)) # Output: {1, 2}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 5, 6}
Modifying Sets
Sets can be modified by adding or removing elements:

add(element): Adds an element to the set.
remove(element): Removes an element from the set; raises KeyError if not found.
discard(element): Removes an element from the set; does nothing if not found.
clear(): Removes all elements from the set.
pop(): Removes and returns a random element from the set.
Examples:
fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}

fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry', 'orange'}

fruits.discard("banana") # No error if "banana" is not in the set
print(fruits) # Output: {'apple', 'cherry', 'orange'}

fruits.clear()
print(fruits) # Output: set()
Frozensets
A frozenset is an immutable version of a set. It cannot be modified after it is created.

Example:
frozen_set = frozenset([1, 2, 3, 4])
print(frozen_set) # Output: frozenset({1, 2, 3, 4})

# Attempting to modify a frozenset will raise an AttributeError
# frozen_set.add(5) # Raises AttributeError
👍2
Practice Exercises for Day 7

Exercise 1: Dictionary Manipulation

Create a dictionary with keys as names and values as marks. Add new entries, update marks, and delete a student entry.


Exercise 2: Word Frequency
Write a Python program to count the frequency of each word in a given sentence using a dictionary.


Exercise 3: Set Operations
Given two lists, create sets from them and perform union, intersection, difference, and symmetric difference operations.


Exercise 4: Unique Elements Finder
Write a Python program to find unique elements in a list using a set.


Exercise 5: Nested Dictionary
Create a nested dictionary to represent students' data, including their names, ages, and subjects. Write a program to print each student's details.