Python Daily Exercises
Python Daily Exercises
Types
1. List
A list is an ordered, mutable (changeable) collection of elements. Lists are one of the most
versatile data structures in Python. Elements in a list can be of any type (integers, strings, etc.),
and they can be modified after creation.
Creating a List
python
Copy code
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
List Operations
1. Accessing elements: You can access elements in a list using the index (0-based
indexing).
python
Copy code
print(numbers[0]) # Output: 1
print(fruits[1]) # Output: banana
python
Copy code
print(numbers[1:4]) # Output: [2, 3, 4] (from index 1 to 3)
3. Modifying elements: You can change elements in a list by assigning a new value to an
index.
python
Copy code
fruits[1] = "blueberry" # Change "banana" to "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
4. Adding elements:
o Use append() to add a single element at the end.
o Use extend() to add multiple elements.
o Use insert() to add an element at a specific position.
python
Copy code
fruits.append("orange") # Adds 'orange' to the end
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']
5. Removing elements:
o Use remove() to remove the first occurrence of a value.
o Use pop() to remove and return the element at a specific index.
o Use clear() to remove all elements.
python
Copy code
fruits.remove("blueberry") # Removes 'blueberry'
print(fruits) # Output: ['apple', 'grape', 'cherry', 'orange']
python
Copy code
print(len(numbers)) # Output: 8
print(3 in numbers) # Output: True
print(10 in numbers) # Output: False
2. Tuple
A tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to
lists but cannot be modified after creation, which makes them useful for read-only data.
Creating a Tuple
python
Copy code
# A tuple of integers
numbers_tuple = (1, 2, 3, 4)
# A tuple of strings
fruits_tuple = ("apple", "banana", "cherry")
# A mixed tuple
mixed_tuple = (1, "apple", 3.14, True)
Tuple Operations
1. Accessing elements: You can access tuple elements in the same way as lists (indexing).
python
Copy code
print(numbers_tuple[0]) # Output: 1
print(fruits_tuple[2]) # Output: cherry
python
Copy code
print(numbers_tuple[1:3]) # Output: (2, 3)
python
Copy code
combined = numbers_tuple + (5, 6, 7) # Concatenation
print(combined) # Output: (1, 2, 3, 4, 5, 6, 7)
python
Copy code
print(len(numbers_tuple)) # Output: 4
print(3 in numbers_tuple) # Output: True
print(10 in numbers_tuple) # Output: False
5. Immutability: Since tuples are immutable, you cannot modify, add, or remove elements
after creation.
python
Copy code
# This will raise an error because tuples are immutable
# numbers_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment
3. Dictionary
A dictionary is an unordered collection of key-value pairs. Keys in a dictionary are unique, and
each key is associated with a value. Dictionaries are useful for storing data that needs to be
mapped by a unique identifier.
Creating a Dictionary
You can create a dictionary by using curly braces {} with key-value pairs separated by colons :.
python
Copy code
# A dictionary with string keys and integer values
person = {"name": "Alice", "age": 25, "city": "New York"}
# A mixed dictionary
mixed_dict = {1: "apple", "two": 2, 3.14: "pi"}
Dictionary Operations
python
Copy code
print(person["name"]) # Output: Alice
print(data[2]) # Output: banana
2. Adding or updating key-value pairs: You can add a new key-value pair or update an
existing one.
python
Copy code
person["job"] = "Engineer" # Adds a new key "job"
person["age"] = 26 # Updates the value of "age"
print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}
3. Removing elements:
o Use del to remove a key-value pair.
o Use pop() to remove a key-value pair and return its value.
o Use clear() to remove all elements from the dictionary.
python
Copy code
del person["city"] # Removes the "city" key
print(person) # Output: {'name': 'Alice', 'age': 26, 'job': 'Engineer'}
python
Copy code
print(len(person)) # Output: 3
print("name" in person) # Output: True
print("city" in person) # Output: False
5. Iterating over a dictionary: You can iterate over keys, values, or key-value pairs using
a for loop.
python
Copy code
# Iterating over keys
for key in person:
print(key) # Output: name, age, job
Conclusion
Lists are mutable, ordered collections of elements that allow for easy modification and
indexing.
Tuples are immutable, ordered collections that cannot be modified after creation.
Dictionaries are unordered collections of key-value pairs, where keys must be unique,
and you can quickly look up values using keys.
Exercise;
Exercise 1: Lists
Exercise 2: Tuples
Exercise 3: Dictionaries
Slicing in Lists
1. Given the list numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], use slicing to:
o Extract the first 4 elements.
o Extract all elements from index 4 onwards.
o Extract the last 3 elements.
o Extract every second element from the list.
2. Given the list letters = ['a', 'b', 'c', 'd', 'e', 'f'], use slicing to:
o Extract elements from index 1 to 4 (inclusive).
o Extract elements from index 2 to the end.
o Reverse the list using slicing.
3. If you have the list items = ['apple', 'banana', 'cherry', 'date', 'elderberry'], use slicing to:
o Get all items except the first one.
o Get all items except the last one.
o Get the middle item (if applicable).
Slicing in Tuples
Slicing in Lists
1. Given the list numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], use slicing to:
o Extract the first 4 elements:
python
Copy code
numbers[:4] # Output: [10, 20, 30, 40]
python
Copy code
numbers[4:] # Output: [50, 60, 70, 80, 90, 100]
python
Copy code
numbers[-3:] # Output: [80, 90, 100]
python
Copy code
numbers[::2] # Output: [10, 30, 50, 70, 90]
2. Given the list letters = ['a', 'b', 'c', 'd', 'e', 'f'], use slicing to:
o Extract elements from index 1 to 4 (inclusive):
python
Copy code
letters[1:5] # Output: ['b', 'c', 'd', 'e']
python
Copy code
letters[2:] # Output: ['c', 'd', 'e', 'f']
python
Copy code
letters[::-1] # Output: ['f', 'e', 'd', 'c', 'b', 'a']
3. If you have the list items = ['apple', 'banana', 'cherry', 'date', 'elderberry'], use slicing to:
o Get all items except the first one:
python
Copy code
items[1:] # Output: ['banana', 'cherry', 'date', 'elderberry']
python
Copy code
items[:-1] # Output: ['apple', 'banana', 'cherry', 'date']
python
Copy code
items[len(items)//2:len(items)//2+1] # Output: ['cherry']
2. Slicing in Tuples
python
Copy code
numbers_tuple[:5] # Output: (1, 2, 3, 4, 5)
python
Copy code
numbers_tuple[3:8] # Output: (4, 5, 6, 7, 8)
python
Copy code
numbers_tuple[::3] # Output: (1, 4, 7)
5. If you have the tuple colors = ('red', 'green', 'blue', 'yellow', 'purple'), use slicing to:
o Extract elements from index 1 to index 3:
python
Copy code
colors[1:4] # Output: ('green', 'blue', 'yellow')
python
Copy code
colors[::-1] # Output: ('purple', 'yellow', 'blue', 'green', 'red')
Exercise 1: Lists
python
Copy code
fruits = ['apple', 'banana', 'mango', 'grape', 'orange']
print(fruits) # Output: ['apple', 'banana', 'mango', 'grape', 'orange']
python
Copy code
fruits[1] = 'strawberry'
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple', 'kiwi']
python
Copy code
fruits.pop() # Removes 'kiwi'
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple']
python
Copy code
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple']
print(len(fruits)) # Output: 6
Exercise 2: Tuples
python
Copy code
numbers_tuple = (10, 20, 30, 40)
print(numbers_tuple) # Output: (10, 20, 30, 40)
python
Copy code
print(numbers_tuple[2]) # Output: 30
3. Create a new tuple by concatenating your existing tuple with another tuple.
python
Copy code
new_tuple = numbers_tuple + (50, 60)
print(new_tuple) # Output: (10, 20, 30, 40, 50, 60)
python
Copy code
print(numbers_tuple[:3]) # Output: (10, 20, 30)
Exercise 3: Dictionaries
python
Copy code
person = {
'name': 'John',
'age': 30,
'city': 'New York'
}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
2. Add a new key-value pair for "job" with the value "Engineer".
python
Copy code
person['job'] = 'Engineer'
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
python
Copy code
person['age'] = 31
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
python
Copy code
del person['city']
print(person) # Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}
python
Copy code
print(person) # Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}
print('name' in person) # Output: True
python
Copy code
mixed_list = [
(1, 2, 3, 4),
{'color': 'blue', 'hex': '#0000FF'}
]
print(mixed_list) # Output: [(1, 2, 3, 4), {'color': 'blue', 'hex': '#0000FF'}]
2. Access and print the values from both the tuple and the dictionary inside the list.
python
Copy code
# Accessing tuple and dictionary values
print(mixed_list[0]) # Output: (1, 2, 3, 4)
print(mixed_list[0][2]) # Output: 3 (Third element of the tuple)
print(mixed_list[1]) # Output: {'color': 'blue', 'hex': '#0000FF'}
print(mixed_list[1]['color']) # Output: 'blue'