Document
Document
List: A list is a built-in data structure in Python that allows you to store a
collection of elements in a specific order. Lists are mutable, which means you
can modify their content after they are created. Lists are defined using square
brackets [], and the elements inside the list are separated by commas.
Example of a list:
2. Dictionary:
A dictionary is a collection of key-value pairs in Python. Each key is unique,
and it is used to access its corresponding value efficiently.
Dictionaries are defined using curly braces { } and key-value pairs are
separated by colons (:).
Example of a dictionary:
The shelve module in Python provides a simple way to persistently store Python program
variables in a file, similar to a dictionary-like structure. It allows you to save and retrieve data
between program executions. This can be useful for caching, storing user preferences, or
saving intermediate results. Let's go through an example to illustrate how to use the shelve
module:
import shelve
def save_data_to_file():
# Data to be saved
names = ['Alice', 'Bob', 'Charlie']
ages = {'Alice': 30, 'Bob': 25, 'Charlie': 22}
favorite_color = 'blue'
def read_data_from_file():
# Opening the existing shelve file in read mode
with shelve.open('data_file') as db:
# Reading variables from the shelve file
names = db['names']
ages = db['ages']
favorite_color = db['favorite_color']
copy.copy() : The copy.copy() method creates a shallow copy of the object, meaning
it duplicates the top-level structure of the object but not the nested objects
inside it.
1. import copy
2.
3. # Example using copy.copy()
4. original_list = [1, 2, [3, 4]]
5.
6. # Creating a shallow copy of the original_list
7. shallow_copy_list = copy.copy(original_list)
8.
9. # Modifying the nested list inside the shallow copy
10. shallow_copy_list[2][0] = 99
11.
12. # The change is reflected in both the original and the shallow copy
13. print("Original List:", original_list) # Output: [1, 2, [99, 4]]
14. print("Shallow Copy List:", shallow_copy_list) # Output: [1, 2, [99, 4]]
As you can see, when we modify the nested list in the shallow copy, the change is also
reflected in the original list.
2. copy.deepcopy(): The copy.deepcopy() method creates a deep copy of the object,
meaning it duplicates the entire object along with all the objects nested inside
it.
3. import copy
4.
5. # Example using copy.deepcopy()
6. original_list = [1, 2, [3, 4]]
7.
8. # Creating a deep copy of the original_list
9. deep_copy_list = copy.deepcopy(original_list)
10.
11. # Modifying the nested list inside the deep copy
12. deep_copy_list[2][0] = 99
13.
14. # The change is NOT reflected in the original list
15. print("Original List:", original_list) # Output: [1, 2, [3, 4]]
16. print("Deep Copy List:", deep_copy_list) # Output: [1, 2, [99, 4]]
As you can see, when we modify the nested list in the deep copy, the original list
remains unchanged.
In summary, copy.copy() creates a shallow copy, which means it copies the top-level
structure but shares the nested objects, whereas copy.deepcopy() creates a deep copy,
duplicating the entire object along with all the nested objects, providing complete
independence between the original and the copy.
1. Lists:
Lists are ordered collections of items, and they are mutable, meaning you can
change, add, or remove elements after creation.
Lists are defined using square brackets [] .
# Example of a list
fruits_list = ['apple', 'banana', 'orange', 'grapes']
# Accessing elements in a list
print(fruits_list[0]) # Output: 'apple'
# Modifying elements in a list
fruits_list[1] = 'kiwi'
print(fruits_list) # Output: ['apple', 'kiwi', 'orange', 'grapes']
# Adding elements to a list
fruits_list.append('pear')
print(fruits_list) # Output: ['apple', 'kiwi', 'orange', 'grapes', 'pear']
# Removing elements from a list
fruits_list.remove('orange')
print(fruits_list) # Output: ['apple', 'kiwi', 'grapes', 'pear']
2. Tuples:
Tuples are ordered collections of items, similar to lists, but they are
immutable, meaning you cannot change their elements after creation.
Tuples are defined using parentheses ().
# Example of a tuple
fruits_tuple = ('apple', 'banana', 'orange', 'grapes')
# Accessing elements in a tuple
print(fruits_tuple[0]) # Output: 'apple'
# Tuples are immutable, so you cannot modify elements
# fruits_tuple[1] = 'kiwi' # This will raise an error
# Concatenating tuples
new_tuple = fruits_tuple + ('pear', 'kiwi')
print(new_tuple) # Output: ('apple', 'banana', 'orange', 'grapes', 'pear', 'kiwi')
3. Dictionaries:
Dictionaries are collections of key-value pairs, and they are mutable.
Dictionaries are defined using curly braces {} and are comprised of key: value
pairs.
# Example of a dictionary
fruits_dict = {
'apple': 3,
'banana': 5,
'orange': 2,
'grapes': 4
}
# Accessing values using keys in a dictionary
print(fruits_dict['apple']) # Output: 3
# Modifying values in a dictionary
fruits_dict['banana'] = 7
print(fruits_dict) # Output: {'apple': 3, 'banana': 7, 'orange': 2, 'grapes': 4}
# Adding new key-value pairs to a dictionary
fruits_dict['pear'] = 6
print(fruits_dict) # Output: {'apple': 3, 'banana': 7, 'orange': 2, 'grapes': 4, 'pear': 6}
# Removing a key-value pair from a dictionary
del fruits_dict['orange']
print(fruits_dict) # Output: {'apple': 3, 'banana': 7, 'grapes': 4, 'pear': 6}
In summary, Lists are mutable ordered collections, Tuples are immutable ordered
collections, and Dictionaries are mutable collections of key-value pairs in Python.
Using string slicing operation write python program to reverse each word in a given
string (eg: input: “hello how are you”, output: “olleh woh erauoy”)
def reverse_words(input_string):
# Split the input string into individual words
words = input_string.split()
# Join the reversed words back to form the final output string
output_string = ' '.join(reversed_words)
return output_string
In the reverse_words function, we first split the input string into individual words using the
split() method, which creates a list of words. Then, using a list comprehension, we reverse
each word in the list using string slicing word[::-1]. Finally, we join the reversed words
back together with spaces using the join() method to form the final output string with
each word reversed.
Exemplify different ways to delete an element from a list with suitable Python syntax
and programming examples.
1. Using del statement: The del statement allows you to remove an element from
a list by specifying its index
2. # Example using del statement
3. fruits = ['apple', 'banana', 'orange', 'grapes']
4.
5. # Deleting the element at index 1 (banana)
6. del fruits[1]
7.
8. print(fruits) # Output: ['apple', 'orange', 'grapes']
Using remove() method: The remove() method removes the first occurrence of a
specified value from the list.
# Example using remove() method
fruits = ['apple', 'banana', 'orange', 'grapes']
3. Using pop() method with index: The pop() method removes and returns the
element at the specified index. If no index is provided, it removes the last
element.
4. # Example using pop() method with index
5. fruits = ['apple', 'banana', 'orange', 'grapes']
6.
7. # Removing and getting the element at index 2 (orange)
8. removed_element = fruits.pop(2)
9.
10. print(fruits) # Output: ['apple', 'banana', 'grapes']
11. print(removed_element) # Output: 'orange'
4. Using pop() method without index: If you use pop() without providing an index,
it removes the last element from the list.
5. # Example using pop() method without index
6. fruits = ['apple', 'banana', 'orange', 'grapes']
7.
8. # Removing and getting the last element (grapes)
9. removed_element = fruits.pop()
10.
11. print(fruits) # Output: ['apple', 'banana', 'orange']
12. print(removed_element) # Output: 'grapes'
5. Using list comprehension to filter elements: You can use list comprehension to create
a new list excluding the element you want to delete.
6. # Example using list comprehension
7. fruits = ['apple', 'banana', 'orange', 'grapes']
8.
9. # Removing the element 'banana' using list comprehension
10. fruits = [fruit for fruit in fruits if fruit != 'banana']
11. print(fruits) # Output: ['apple', 'orange', 'grapes']