Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Daily Exercises

The document provides a detailed explanation of three fundamental data structures in Python: lists, tuples, and dictionaries. It covers their characteristics, how to create them, and various operations such as accessing, modifying, and removing elements. Additionally, it includes exercises for practicing the use of these data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Daily Exercises

The document provides a detailed explanation of three fundamental data structures in Python: lists, tuples, and dictionaries. It covers their characteristics, how to create them, and various operations such as accessing, modifying, and removing elements. Additionally, it includes exercises for practicing the use of these data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Python daily exercises

Types

Detailed Explanation of Lists, Tuples, and Dictionaries in Python

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

You can create a list by enclosing elements in square brackets [].

python
Copy code
# A list of integers
numbers = [1, 2, 3, 4, 5]

# A list of strings
fruits = ["apple", "banana", "cherry"]

# A mixed list (integers, strings, and floats)


mixed = [1, "apple", 3.14, True]

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

2. Slicing a list: Extract a portion of the list using slicing.

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']

numbers.extend([6, 7, 8]) # Adds multiple elements


print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8]

fruits.insert(1, "grape") # Adds 'grape' at index 1


print(fruits) # Output: ['apple', 'grape', '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']

removed_item = fruits.pop(2) # Removes and returns the element at index 2


print(removed_item) # Output: cherry
print(fruits) # Output: ['apple', 'grape', 'orange']

fruits.clear() # Removes all elements from the list


print(fruits) # Output: []

6. List Length and Membership:


o Use len() to get the length of a list.
o Use in to check if an element exists in a list.

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

You can create a tuple by enclosing elements in parentheses ().

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

2. Slicing a tuple: Similar to lists, tuples can also be sliced.

python
Copy code
print(numbers_tuple[1:3]) # Output: (2, 3)

3. Concatenation and repetition:


o Use + to concatenate two tuples.
o Use * to repeat a tuple.

python
Copy code
combined = numbers_tuple + (5, 6, 7) # Concatenation
print(combined) # Output: (1, 2, 3, 4, 5, 6, 7)

repeated = (1, 2) * 3 # Repeating the tuple


print(repeated) # Output: (1, 2, 1, 2, 1, 2)

4. Tuple Length and Membership:


o Use len() to get the length of a tuple.
o Use in to check if an element exists in a tuple.

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 dictionary with integer keys and string values


data = {1: "apple", 2: "banana", 3: "cherry"}

# A mixed dictionary
mixed_dict = {1: "apple", "two": 2, 3.14: "pi"}

Dictionary Operations

1. Accessing values: You can access values by their keys.

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'}

removed_value = person.pop("job") # Removes and returns the value of "job"


print(removed_value) # Output: Engineer
print(person) # Output: {'name': 'Alice', 'age': 26}

person.clear() # Removes all key-value pairs


print(person) # Output: {}

4. Dictionary Length and Membership:


o Use len() to get the number of key-value pairs.
o Use in to check if a key exists in a dictionary.

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

# Iterating over values


for value in person.values():
print(value) # Output: Alice, 26, Engineer

# Iterating over key-value pairs


for key, value in person.items():
print(key, value)
# Output: name Alice
# age 26
# job Engineer

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

1. Create a list of 5 of your favorite fruits.


2. Add two more fruits to the list.
3. Replace the second fruit in the list with another fruit.
4. Remove the last fruit from the list.
5. Print the list and the number of fruits in it.

Exercise 2: Tuples

1. Create a tuple with 4 numbers of your choice.


2. Access and print the third element in the tuple.
3. Create a new tuple by concatenating your existing tuple with another tuple.
4. Try to modify an element in the tuple (this should give an error).
5. Slice the tuple and print the first three elements.

Exercise 3: Dictionaries

1. Create a dictionary representing a person with the following details:


o Name: "John"
o Age: 30
o City: "New York"
2. Add a new key-value pair for "job" with the value "Engineer".
3. Change the age to 31.
4. Remove the "city" key.
5. Print the dictionary and check if "name" is a key in the dictionary.

Bonus Exercise: Mixed Data Structures


1. Create a list that contains:
o A tuple of numbers
o A dictionary with your favorite color and its hexadecimal value
2. Access and print the values from both the tuple and the dictionary inside the list.

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

4. Given the tuple numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9), use slicing to:


o Extract the first 5 elements.
o Extract elements from index 3 to index 7.
o Extract every third element.
5. If you have the tuple colors = ('red', 'green', 'blue', 'yellow', 'purple'), use slicing to:
o Extract elements from index 1 to index 3.
o Reverse the tuple.

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]

o Extract all elements from index 4 onwards:

python
Copy code
numbers[4:] # Output: [50, 60, 70, 80, 90, 100]

o Extract the last 3 elements:

python
Copy code
numbers[-3:] # Output: [80, 90, 100]

o Extract every second element:

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']

o Extract elements from index 2 to the end:

python
Copy code
letters[2:] # Output: ['c', 'd', 'e', 'f']

o Reverse the list using slicing:

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']

o Get all items except the last one:

python
Copy code
items[:-1] # Output: ['apple', 'banana', 'cherry', 'date']

o Get the middle item (if applicable):

python
Copy code
items[len(items)//2:len(items)//2+1] # Output: ['cherry']

2. Slicing in Tuples

4. Given the tuple numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9), use slicing to:


o Extract the first 5 elements:

python
Copy code
numbers_tuple[:5] # Output: (1, 2, 3, 4, 5)

o Extract elements from index 3 to index 7:

python
Copy code
numbers_tuple[3:8] # Output: (4, 5, 6, 7, 8)

o Extract every third element:

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')

o Reverse the tuple:

python
Copy code
colors[::-1] # Output: ('purple', 'yellow', 'blue', 'green', 'red')

Exercise 1: Lists

1. Create a list of 5 of your favorite fruits.

python
Copy code
fruits = ['apple', 'banana', 'mango', 'grape', 'orange']
print(fruits) # Output: ['apple', 'banana', 'mango', 'grape', 'orange']

2. Add two more fruits to the list.


python
Copy code
fruits.append('pineapple')
fruits.append('kiwi')
print(fruits) # Output: ['apple', 'banana', 'mango', 'grape', 'orange', 'pineapple', 'kiwi']

3. Replace the second fruit in the list with another fruit.

python
Copy code
fruits[1] = 'strawberry'
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple', 'kiwi']

4. Remove the last fruit from the list.

python
Copy code
fruits.pop() # Removes 'kiwi'
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple']

5. Print the list and the number of fruits in it.

python
Copy code
print(fruits) # Output: ['apple', 'strawberry', 'mango', 'grape', 'orange', 'pineapple']
print(len(fruits)) # Output: 6

Exercise 2: Tuples

1. Create a tuple with 4 numbers of your choice.

python
Copy code
numbers_tuple = (10, 20, 30, 40)
print(numbers_tuple) # Output: (10, 20, 30, 40)

2. Access and print the third element in the tuple.

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)

4. Try to modify an element in the tuple (this should give an error).


python
Copy code
# Uncommenting the following line will give an error:
# numbers_tuple[1] = 25
# TypeError: 'tuple' object does not support item assignment

5. Slice the tuple and print the first three elements.

python
Copy code
print(numbers_tuple[:3]) # Output: (10, 20, 30)

Exercise 3: Dictionaries

1. Create a dictionary representing a person with the following details:

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'}

3. Change the age to 31.

python
Copy code
person['age'] = 31
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'job': 'Engineer'}

4. Remove the "city" key.

python
Copy code
del person['city']
print(person) # Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}

5. Print the dictionary and check if "name" is a key in the dictionary.

python
Copy code
print(person) # Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}
print('name' in person) # Output: True

Bonus Exercise: Mixed Data Structures

1. Create a list that contains:


o A tuple of numbers
o A dictionary with your favorite color and its hexadecimal value

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'

You might also like