Summary
Today, we covered loops in Python, a fundamental concept for automating repetitive tasks:
-
-
- Loop control statements (
- Nested loops are used for complex iterations within iterations.
Today, we covered loops in Python, a fundamental concept for automating repetitive tasks:
-
while loops are used when the number of iterations is not known beforehand.-
for loops are used to iterate over a sequence and are most useful when the number of iterations is known.- Loop control statements (
break, continue, pass) help modify the flow of loops.- Nested loops are used for complex iterations within iterations.
Introduction to Lists
Syntax:
Example:
A list is a versatile, ordered collection in Python that can store a sequence of items. Lists are mutable, meaning their contents can be changed after they are created.
Syntax:
my_list = [item1, item2, item3, ...]
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
🥰1
List Indexing and Slicing
Example:
Example:
Indexing: Access individual elements in a list using their index (starting from 0).
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
Slicing: Access a subset of elements using a range of indices.
Example:
print(fruits[0:2]) # Output: ['apple', 'banana']
Common List Methods
Lists come with several built-in methods to perform common operationsappend(item): Adds an item to the end of the list.
Example:
Lists come with several built-in methods to perform common operationsappend(item): Adds an item to the end of the list.
insert(index, item): Inserts an item at a specified index.remove(item): Removes the first occurrence of an item.pop(index): Removes and returns the item at the specified index. If no index is provided, it removes the last item.sort(): Sorts the list in ascending order.reverse(): Reverses the order of the list.index(item): Returns the index of the first occurrence of an item.count(item): Returns the number of times an item appears in the list.clear(): Removes all elements from the list.Example:
numbers = [3, 1, 4, 1, 5, 9]
numbers.append(2)
print(numbers) # Output: [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
numbers.pop()
print(numbers) # Output: [1, 1, 2, 3, 4, 5]
List Comprehensions
Syntax:
Example:
List comprehensions provide a concise way to create lists. It can be used to apply an expression to each item in an iterable.
Syntax:
new_list = [expression for item in iterable if condition]
Example:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Nested Lists
Example:
A nested list is a list that contains another list as its element.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1]) # Output: [4, 5, 6]
print(matrix[1][1]) # Output: 5
Introduction to Tuples
Syntax:
Example:
A tuple is similar to a list but is immutable, meaning it cannot be modified after creation. Tuples are used for fixed collections of items.
Syntax:
my_tuple = (item1, item2, item3, ...)
Example:
colors = ("red", "green", "blue")
print(colors) # Output: ('red', 'green', 'blue')Accessing Tuple Elements
Example:
Like lists, tuples can be indexed and sliced.
Example:
print(colors[0]) # Output: red
print(colors[0:2]) # Output: ('red', 'green')
Tuple Methods
Tuples have fewer built-in methods compared to lists since they are immutable:
Example:
Tuples have fewer built-in methods compared to lists since they are immutable:
count(item): Returns the number of times an item appears in the tuple.index(item): Returns the index of the first occurrence of an item.Example:
t = (1, 2, 3, 1, 2)
print(t.count(1)) # Output: 2
print(t.index(3)) # Output: 2
👍1
Converting Between Lists and Tuples
Examples:
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
Example:
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
Exercise 2: Find the Largest Number in a List
Exercise 3: Tuple Packing and Unpacking
Exercise 4: List Comprehensions
Exercise 5: Matrix Operations
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:
Tuple-Based Menu:
Flatten a Nested List:
Unique Elements Finder:
Tuple Manipulation:
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!
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)
print(i)
Anonymous Quiz
27%
1 2 3
67%
0 1 2
7%
0 1 2 3
0%
3 2 1
Which of the following statements about while loops is true in Python?
Anonymous Quiz
12%
A while loop always runs indefinitely.
68%
A while loop runs as long as a specified condition is True.
8%
A while loop can only be used with numbers.
12%
A while loop is the same as a for loop
Free Python Course | Programming Tutorials
Nested Loops A loop inside another loop is called a nested loop. The inner loop runs completely whenever the outer loop runs once. Example: for i in range(1, 4): for j in range(1, 4): print(f"i={i}, j={j}") Output: i=1, j=1 i=1, j=2 i=1, j=3 i=2…
Which statement about nested loops is correct?
Anonymous Quiz
19%
Nested loops always result in exponential time complexity.
15%
Nested loops are only used for working with multidimensional arrays.
59%
The inner loop executes completely every time the outer loop runs one iteration.
7%
Python does not support nested loops.
❤1
Introduction to Dictionaries
Syntax:
Example:
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
Example:
Example:
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