[go: up one dir, main page]

0% found this document useful (0 votes)
630 views7 pages

Document

Here are some common ways to delete an element from a list in Python with examples: 1. Using the remove() method: ```python fruits = ['apple', 'banana', 'orange', 'grapes'] fruits.remove('banana') print(fruits) # ['apple', 'orange', 'grapes'] ``` 2. Using pop() and specifying the index: ```python fruits = ['apple', 'banana', 'orange', 'grapes'] fruits.pop(1) print(fruits) # ['apple', 'orange', 'grapes'] ``` 3. Using del statement and specifying the index:

Uploaded by

Lakshmi Hj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
630 views7 pages

Document

Here are some common ways to delete an element from a list in Python with examples: 1. Using the remove() method: ```python fruits = ['apple', 'banana', 'orange', 'grapes'] fruits.remove('banana') print(fruits) # ['apple', 'orange', 'grapes'] ``` 2. Using pop() and specifying the index: ```python fruits = ['apple', 'banana', 'orange', 'grapes'] fruits.pop(1) print(fruits) # ['apple', 'orange', 'grapes'] ``` 3. Using del statement and specifying the index:

Uploaded by

Lakshmi Hj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

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:

# Creating a list of integers


numbers = [1, 2, 3, 4, 5]

# Adding elements to the list


numbers.append(6)
numbers.extend([7, 8])

# Accessing elements in the list


print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3

# Modifying elements in the list


numbers[1] = 10

# Removing elements from the list


numbers.remove(4)
numbers.pop(0)

# Length of the list


print(len(numbers)) # Output: 6

# Iterating through the list


for num in numbers:
print(num)

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:

# Creating a dictionary of student names and their ages


student_ages = {
'Alice': 20,
'Bob': 22,
'Charlie': 19,
'Eve': 21
}
# Accessing values using keys
print(student_ages['Bob']) # Output: 22

# Modifying values in the dictionary


student_ages['Charlie'] = 20

# Adding new key-value pairs


student_ages['David'] = 18

# Checking if a key exists in the dictionary


if 'Eve' in student_ages:
print("Eve's age:", student_ages['Eve'])

# Removing a key-value pair from the dictionary


removed_age = student_ages.pop('Bob')
print("Removed age:", removed_age)

# Length of the dictionary


print(len(student_ages)) # Output: 4

# Iterating through the dictionary keys and values


for name, age in student_ages.items():
print(f"{name} is {age} years old.")

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'

# Creating and opening a shelve file in write mode


with shelve.open('data_file') as db:
# Saving variables to the shelve file
db['names'] = names
db['ages'] = ages
db['favorite_color'] = favorite_color

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

# Printing the retrieved data


print("Names:", names)
print("Ages:", ages)
print("Favorite Color:", favorite_color)

# Saving data to the shelve file


save_data_to_file()

# Reading data from the shelve file


read_data_from_file()

In this example, we have defined two functions: save_data_to_file() and read_data_from_file() .


The save_data_to_file() function demonstrates how to save Python variables (a list, a
dictionary, and a string) to a shelve file called "data_file". We open the shelve file in write
mode using shelve.open() and use dictionary-like syntax to save the variables. The
read_data_from_file() function demonstrates how to read the saved data back from the shelve
file. We open the shelve file in read mode using shelve.open() and again use dictionary-like
syntax to retrieve the variables. Keep in mind that the shelve module is not suitable for large-
scale or high-performance data storage, as it uses the pickle module internally, which may
not be the most efficient serialization method. For more advanced use cases, consider using
other database libraries or formats

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

# Reverse each word using string slicing


reversed_words = [word[::-1] for word in words]

# Join the reversed words back to form the final output string
output_string = ' '.join(reversed_words)

return output_string

# Test the function


input_string = "hello how are you"
output_string = reverse_words(input_string)
print(output_string) # Output: "olleh woh era uoy"

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

# Removing the element 'orange'


fruits.remove('orange')

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

You might also like