Python Module 2 (YouTube Manoj P N)
Python Module 2 (YouTube Manoj P N)
1. Explain the methods of List data type in Python for the following operations
with suitable code snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list
ANS:
Python lists:
The list is a built-in data type used to store collections of items. Lists are one of
the most versatile and commonly used data structures in Python. They are used to
hold an ordered collection of elements, and these elements can be of any data
type, including numbers, strings, other lists, or even more complex objects. Lists
are mutable, which means you can change their contents by adding, removing, or
modifying elements.
Append: The append() method adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
# Resulting list: [1, 2, 3, 4]
Insert: The insert() method inserts an element at a specific index in the list.
Example:
my_list = [1, 2, 3]
my_list.insert(1, 4) # Insert 4 at index 1
# Resulting list: [1, 4, 2, 3]
(ii) Removing Values from a List:
Remove: The remove() method removes the first occurrence of a specified value.
Example:
my_list = [1, 2, 3, 2]
my_list.remove(2) # Removes the first occurrence of 2
# Resulting list: [1, 3, 2]
Pop: The pop() method removes and returns the element at a specified index. If no
index is provided, it removes and returns the last element.
Example:
my_list = [1, 2, 3]
value = my_list.pop(1) # Removes and returns the element at index 1 (2)
# Resulting list: [1, 3], value: 2
Del Statement: The del statement can delete elements by index or even the
entire list.
Example:
my_list = [1, 2, 3]
del my_list[1] # Deletes element at index 1 (2)
# Resulting list: [1, 3]
my_list = [1, 2, 3]
del my_list # Deletes the entire list
# Results in an error if you try to access my_list afterward
(iii) Finding a Value in a List:
To find a value in a list, you can use the in operator or the index() method:
Using in Operator:
Example:
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
print("3 is in the list.")
Using index() Method:
Example:
Copy codmy_list = [1, 2, 3, 4, 5]
index = my_list.index(3) # Returns the index of the first occurrence of 3
print("Index of 3:", index)
List Methods:
append() Method:
index() returns the index of the first occurrence of a specified element in the list.
Syntax: list.index(element)
Example:
my_list = [10, 20, 30, 20, 40]
index = my_list.index(20) # Returns the index of the first 20 (1)
remove() Method:
remove() removes the first occurrence of a specified element from the list.
Syntax: list.remove(element)
Example:
my_list = [10, 20, 30, 20, 40]
my_list.remove(20) # Removes the first 20
# Resulting list: [10, 30, 20, 40]
Differences Between List and Tuple:
Mutability:
List: Lists are mutable, which means you can change their contents (add, remove, or
modify elements).
Tuple: Tuples are immutable, and their contents cannot be modified once created.
Syntax:
Lists are used for collections of items where elements can change or need to be
modified.
Tuples are used for collections that should not change, like coordinates or records.
Converting a List to a Tuple:
To convert a list to a tuple in Python, you can use the tuple() constructor, passing
the list as an argument. Here's an example:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
# my_list is [1, 2, 3], and my_tuple is (1, 2, 3)
This creates a new tuple with the same elements as the original list. The resulting
tuple is immutable, and its elements cannot be changed.
3.What is a string? Explain any four methods associated with string and
explain each of them with an example.
ANS:
What is a String?:
Here are four common string methods along with explanations and examples:
1. len() Method:
The len() method is used to get the length (the number of characters) of a string.
Syntax: len(string)
Example:
text = "Hello, World!"
length = len(text)
print(length) # Output: 13
2. upper() Method:
Syntax: string.lower()
Example:
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # Output: "hello, world!"
4. replace() Method:
ANS:
Traversing a list means visiting each element of the list to perform some
operation, such as printing, modifying, or searching. There are several ways to
traverse a list in Python.
You can use a for loop to iterate through the elements of a list one by one.
Example:
my_list = [1, 2, 3, 4, 5]
You can use a while loop along with an index to traverse a list.
Example:
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
In this example, a while loop is used with an index variable to iterate through
my_list. The loop continues until the index reaches the length of the list.
Example:
my_list = [1, 2, 3, 4, 5]
4. Using Enumerate:
The enumerate() function can be used to traverse a list while keeping track of the
index.
Example:
my_list = [10, 20, 30, 40, 50]
Example:
my_list = [1, 2, 3, 4, 5]
ANS:
A dictionary in Python is a built-in data type that represents an unordered
collection of key-value pairs. It is also known as an associative array or a hash map.
Dictionaries are used to store and retrieve data based on keys rather than indices.
Each key in a dictionary maps to a specific value, and you can use keys to access,
modify, and delete values in the dictionary. Dictionaries are enclosed in curly
braces {} and consist of key-value pairs separated by colons.
List:
Dictionary Methods:
get() Method:
The get() method retrieves the value associated with a specified key. It allows you
to provide a default value if the key doesn't exist in the dictionary.
Syntax: dictionary.get(key, default_value)
Example:
The items() method returns a view of all key-value pairs in the dictionary as tuples.
Syntax: dictionary.items()
Example:
student_scores = {"Alice": 90, "Bob": 85, "Charlie": 88}
score_pairs = student_scores.items()
# Returns a view: dict_items([('Alice', 90), ('Bob', 85), ('Charlie', 88)])
keys() Method: