Docs
Python
Unit 3

1. What is data structure? Which data structure used by Python?

A data structure is a way of organizing, storing, and manipulating data in a computer program. It provides a way to access and manipulate data efficiently, making it easier for programmers to write efficient algorithms and programs.

Python provides several built-in data structures that are used to store collections of data. These include:

  1. Lists: A list is a collection of values that are ordered and mutable. Lists are created using square brackets [] and can contain elements of different data types.
  2. Tuples: A tuple is a collection of values that are ordered and immutable. Tuples are created using parentheses () and can contain elements of different data types.
  3. Dictionaries: A dictionary is a collection of key-value pairs that are unordered and mutable. Dictionaries are created using curly braces {} and can contain elements of different data types.
  4. Sets: A set is a collection of unique values that are unordered and mutable. Sets are created using curly braces or the set() function.

2. How to define and access the elements of list?

In Python, a list is defined using square brackets [ ] and can contain elements of different data types separated by commas. Here's an example of defining a list:

vros.py
my_list = [1, 2, 3, 'hello', 'world']

To access the elements of a list, you can use indexing. In Python, indexing starts at 0 for the first element, and negative indexing starts at -1 for the last element. Here are some examples of accessing list elements:

vros.py
my_list = [1, 2, 3, 'hello', 'world']
 
# Accessing the first element
print(my_list[0])   # Output: 1
 
# Accessing the last element
print(my_list[-1])  # Output: 'world'
 
# Accessing a range of elements
print(my_list[1:4]) # Output: [2, 3, 'hello']

In the first example, we access the first element of the list by using index 0. In the second example, we access the last element of the list by using negative index -1. In the third example, we access a range of elements from index 1 to 3 (excluding index 4) using slicing.

You can also modify the elements of a list by using indexing. Here's an example of modifying the second element of the list:

vros.py
my_list = [1, 2, 3, 'hello', 'world']
 
# Modifying the second element
my_list[1] = 'Python'
 
# Printing the modified list
print(my_list) # Output: [1, 'Python', 3, 'hello', 'world']

In this example, we use indexing to modify the second element of the list to the string 'Python'.


3. What is list? How to create list?

In Python, a list is a built-in data structure that is used to store a collection of items. A list can contain elements of different data types, such as integers, floats, strings, or other objects, and the elements can be accessed by their index.

To create a list in Python, you can use square brackets [] and separate the items with commas. Here is an example of creating a list of integers:

vros.py
my_list = [1, 2, 3, 4, 5]

You can also create a list of strings or a mixed list of different data types:

vros.py
string_list = ["apple", "banana", "cherry"]
mixed_list = ["apple", 1, 3.14, True]

You can also create an empty list and add elements to it later:

vros.py
empty_list = []
empty_list.append(1)
empty_list.append("apple")

This will create an empty list and add the integer 1 and the string "apple" to the list using the append() method.

You can also create a list using a for loop and a range of numbers:

vros.py
number_list = [i for i in range(1, 6)]

This will create a list of numbers from 1 to 5.

Overall, lists are a versatile data structure in Python that can be easily created and manipulated, and are widely used in many different types of programs.


4. What are the different operations that can be performed on a list? Explain with examples.

In Python, there are several operations that can be performed on a list. Here are some of the most common operations with examples:

  1. Accessing Elements:

You can access individual elements of a list by their index, starting from 0. Negative indices can be used to count from the end of the list.

vros.py
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 5
  1. Slicing:

You can extract a slice of a list using the syntax my_list[start:stop:step]. The start index is inclusive, the stop index is exclusive, and the step value determines the increment between each element. Omitting these values defaults to the beginning and end of the list with a step of 1.

vros.py
my_list = [1, 2, 3, 4, 5]
print(my_list[1:3]) # Output: [2, 3]
print(my_list[:3]) # Output: [1, 2, 3]
print(my_list[::2]) # Output: [1, 3, 5]
  1. Modifying Elements:

You can modify individual elements of a list by their index or a slice of elements using the assignment operator.

vros.py
my_list = [1, 2, 3, 4, 5]
my_list[2] = "three"
print(my_list) # Output: [1, 2, 'three', 4, 5]
my_list[1:4] = [10, 20, 30]
print(my_list) # Output: [1, 10, 20, 30, 5]
  1. Adding Elements:

You can add elements to the end of a list using the append() method or extend a list with another list using the extend() method.

vros.py
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
my_list.extend([7, 8, 9])
print(my_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. Removing Elements:

You can remove elements from a list using the remove() method or remove the last element using the pop() method.

vros.py
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]
popped_element = my_list.pop()
print(my_list) # Output: [1, 2, 4]
print(popped_element) # Output: 5

5. Explain any two methods under lists in Python with examples.

Here are two methods under lists in Python with examples:

  1. Append(): The append() method is used to add an item to the end of a list. The syntax for using the append() method is as follows:
vros.py
list_name.append(item)

where list_name is the name of the list to which you want to add the item, and item is the item that you want to add to the list. Here's an example:

vros.py
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

Output:

vros.py
pythonCopy code
["apple", "banana", "cherry", "orange"]

In this example, we have a list of fruits, and we use the append() method to add "orange" to the end of the list.

  1. Remove(): The remove() method is used to remove the first occurrence of a specified item from a list. The syntax for using the remove() method is as follows:
vros.py
list_name.remove(item)

where list_name is the name of the list from which you want to remove the item, and item is the item that you want to remove from the list. Here's an example:

vros.py
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana")
print(fruits)

Output:

vros.py
["apple", "cherry", "orange"]

In this example, we have a list of fruits, and we use the remove() method to remove "banana" from the list.


6. Write a Python program to describe different ways of deleting an element from the given list.

here's a Python program that demonstrates different ways of deleting an element from a list:

vros.py
# Method 1: Using the remove() method
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana")
print("Method 1:", fruits)
 
# Method 2: Using the del keyword
fruits = ["apple", "banana", "cherry", "orange"]
del fruits[1]
print("Method 2:", fruits)
 
# Method 3: Using the pop() method
fruits = ["apple", "banana", "cherry", "orange"]
fruits.pop(1)
print("Method 3:", fruits)
 
# Method 4: Using a list comprehension
fruits = ["apple", "banana", "cherry", "orange"]
fruits = [fruit for fruit in fruits if fruit != "banana"]
print("Method 4:", fruits)

Output:

vros.py
Method 1: ['apple', 'cherry', 'orange']
Method 2: ['apple', 'cherry', 'orange']
Method 3: ['apple', 'cherry', 'orange']
Method 4: ['apple', 'cherry', 'orange']

In this program, we have a list of fruits, and we demonstrate four different ways to delete the element "banana" from the list.

Method 1 uses the remove() method, which removes the first occurrence of the specified element from the list.

Method 2 uses the del keyword, which deletes the element at the specified index from the list.

Method 3 uses the pop() method, which removes and returns the element at the specified index from the list.

Method 4 uses a list comprehension to create a new list that contains all elements from the original list except for the specified element.


7. What is tuple in Python? How to create and access it?

In Python, a tuple is an immutable sequence of values. This means that once a tuple is created, its values cannot be changed. Tuples are often used to represent collections of related values, such as the x and y coordinates of a point.

To create a tuple in Python, you can enclose a comma-separated sequence of values in parentheses, like this:

vros.py
my_tuple = (1, 2, 3)

You can also create a tuple by using the built-in tuple() function, like this:

vros.py
my_tuple = tuple([1, 2, 3])

To access the elements of a tuple in Python, you can use square brackets with the index of the element you want to access, starting from 0. For example:

vros.py
my_tuple = (1, 2, 3)
print(my_tuple[0])  # Output: 1
print(my_tuple[1])  # Output: 2
print(my_tuple[2])  # Output: 3

You can also use negative indexing to access elements from the end of the tuple, like this:

vros.py
my_tuple = (1, 2, 3)
print(my_tuple[-1])  # Output: 3
print(my_tuple[-2])  # Output: 2
print(my_tuple[-3])  # Output: 1

Finally, you can use slicing to access a range of elements from a tuple. Slicing works in the same way as it does for lists:

vros.py
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:3])  # Output: (2, 3)
print(my_tuple[:3])  # Output: (1, 2, 3)
print(my_tuple[3:])  # Output: (4, 5)

8. What are mutable and immutable types?

In Python, mutable and immutable are two different types of objects that behave differently when it comes to changing their values.

An immutable object is an object whose value cannot be changed once it is created. Examples of immutable objects in Python include integers, floats, strings, and tuples. When you assign a new value to an immutable object, Python creates a new object rather than modifying the original one.

For example, consider the following code:

vros.py
a = 5
b = a
a = 10
print(a)  # Output: 10
print(b)  # Output: 5

In this code, we first assign the value 5 to the variable a. We then assign the value of a to the variable b. Finally, we assign the value 10 to a. Since integers are immutable in Python, this creates a new object with the value 10, rather than modifying the existing object. Therefore, when we print the values of a and b, we see that a is 10 and b is still 5.

A mutable object, on the other hand, is an object whose value can be changed after it is created. Examples of mutable objects in Python include lists, dictionaries, and sets. When you modify the value of a mutable object, the original object is modified, rather than creating a new object.

For example, consider the following code:

vros.py
my_list = [1, 2, 3]
your_list = my_list
my_list.append(4)
print(my_list)     # Output: [1, 2, 3, 4]
print(your_list)   # Output: [1, 2, 3, 4]

In this code, we first create a list my_list with the values 1, 2, and 3. We then assign my_list to your_list. Finally, we use the append() method to add the value 4 to my_list. Since lists are mutable in Python, this modifies the original object. Therefore, when we print both my_list and your_list, we see that both contain the value 4 at the end.


9. Is tuple mutable? Demonstrate any two methods of tuple.

No, tuples are immutable in Python, which means that their values cannot be modified after they are created. Once a tuple is created, you cannot add, remove, or change elements in it.

Here are two examples of methods that can be used with tuples:

  1. count(): The count() method returns the number of times a specified element appears in a tuple. For example:
vros.py
my_tuple = (1, 2, 3, 4, 3, 5, 3)
count_3 = my_tuple.count(3)
print(count_3) # Output: 3

In this example, the count() method is called on the tuple my_tuple to count the number of times the value 3 appears in it.

  1. index(): The index() method returns the index of the first occurrence of a specified element in a tuple. For example:
vros.py
my_tuple = ('apple', 'banana', 'cherry', 'banana')
index_banana = my_tuple.index('banana')
print(index_banana) # Output: 1

In this example, the index() method is called on the tuple my_tuple to find the index of the first occurrence of the value 'banana' in it. The method returns the index 1, which is the position of the first 'banana' element in the tuple.


10. Write in brief about Tuple in Python. Write operations with suitable examples.

A tuple is a built-in data type in Python that is similar to a list in many ways, but with one crucial difference: tuples are immutable. Once a tuple is created, it cannot be changed. This means that you cannot add, remove, or modify elements in a tuple.

Here are some examples of operations that can be performed with tuples:

  1. Creating a Tuple: A tuple is created by enclosing a sequence of values in parentheses, separated by commas. For example:
vros.py
my_tuple = (1, 2, 3, 4, 5)

This creates a tuple with the values 1, 2, 3, 4, and 5.

  1. Accessing Elements: Elements in a tuple can be accessed using indexing, just like with lists. For example:
vros.py
my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[1]) # Output: banana

This prints the second element in the tuple, which is 'banana'.

  1. Slicing Tuples: Tuples can be sliced using the same syntax as with lists. For example:
vros.py
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)

This prints a new tuple with the elements from index 1 to index 4 (excluding index 4).

  1. Tuple Concatenation: Two or more tuples can be concatenated using the + operator. For example:
vros.py
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(tuple3) # Output: (1, 2, 3, 4, 5, 6)

This creates a new tuple tuple3 that contains all the elements from tuple1 and tuple2.

  1. Tuple Repetition: A tuple can be repeated a certain number of times using the * operator. For example:
vros.py
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

This creates a new tuple repeated_tuple that contains three copies of the elements from my_tuple.

  1. Tuple Unpacking: The values in a tuple can be unpacked into separate variables. For example:
vros.py
my_tuple = ('apple', 'banana', 'cherry')
a, b, c = my_tuple
print(a) # Output: apple
print(b) # Output: banana
print(c) # Output: cherry

This unpacks the values from my_tuple into the variables a, b, and c.


11. Write in brief about Set in Python. Write operations with suitable examples.

A set is a built-in data type in Python that represents an unordered collection of unique elements. Sets are similar to lists and tuples, but unlike lists and tuples, they are unordered and do not allow duplicate elements. Sets are represented by curly braces {} or the set() function.

Here are some examples of operations that can be performed with sets:

  1. Creating a Set: A set is created by enclosing a sequence of values in curly braces {}, separated by commas. For example:
vros.py
my_set = {1, 2, 3, 4, 5}

This creates a set with the values 1, 2, 3, 4, and 5.

  1. Adding Elements: Elements can be added to a set using the add() method. For example:
vros.py
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

This adds the value 4 to the set my_set.

  1. Removing Elements: Elements can be removed from a set using the remove() method. For example:
vros.py
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4}

This removes the value 3 from the set my_set.

  1. Union of Sets: The union of two or more sets can be computed using the union() method or the | operator. For example:
vros.py
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}

This creates a new set union_set that contains all the elements from set1 and set2.

  1. Intersection of Sets: The intersection of two or more sets can be computed using the intersection() method or the & operator. For example:
vros.py
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}

This creates a new set intersection_set that contains only the elements that are in both set1 and set2.

  1. Difference of Sets: The difference between two sets can be computed using the difference() method or the `` operator. For example:
vros.py
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}

This creates a new set difference_set that contains only the elements that are in set1 but not in set2.


12. Explain the properties of dictionary keys.

In Python dictionaries, keys must be unique and immutable objects. Here are the key properties of dictionary keys:

  1. Unique: Each key in a dictionary must be unique. If you try to create a dictionary with duplicate keys, the last value associated with the duplicate key will overwrite the previous value. For example:
vros.py
my_dict = {'a': 1, 'b': 2, 'a': 3}
print(my_dict)  # Output: {'a': 3, 'b': 2}
  1. Immutable: Dictionary keys must be immutable. This means that the keys cannot be changed once they are created. Examples of immutable objects in Python include strings, integers, and tuples. Lists, sets, and dictionaries are mutable and cannot be used as dictionary keys. For example:
vros.py
my_dict = {[1, 2]: 'value'}  # TypeError: unhashable type: 'list'
  1. Hashable: Dictionary keys must be hashable. This means that the keys must have a hash value that does not change during the lifetime of the key. Immutable objects such as strings and tuples are hashable, but mutable objects such as lists and sets are not hashable.
vros.py
my_dict = {('a', 'b'): 1, ['c', 'd']: 2}  # TypeError: unhashable type: 'list'

In summary, dictionary keys in Python must be unique, immutable, and hashable.


13. Explain directory methods in Python.

In Python, a dictionary is a collection of key-value pairs, and it is implemented as a hash table. A dictionary provides several methods for manipulating its contents. Here are some of the most commonly used dictionary methods in Python:

  1. clear(): Removes all the items from the dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict)  # Output: {}
  1. copy(): Returns a shallow copy of the dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = my_dict.copy()
print(new_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}
  1. get(key, default): Returns the value of the specified key. If the key is not found, it returns the default value.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.get('b', 0))  # Output: 2
print(my_dict.get('d', 0))  # Output: 0
  1. items(): Returns a list of key-value pairs.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.items())  # Output: [('a', 1), ('b', 2), ('c', 3)]
  1. keys(): Returns a list of keys in the dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys())  # Output: ['a', 'b', 'c']
  1. values(): Returns a list of values in the dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.values())  # Output: [1, 2, 3]
  1. pop(key, default): Removes the specified key and returns the corresponding value. If the key is not found, it returns the default value.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.pop('b', 0))  # Output: 2
print(my_dict.pop('d', 0))  # Output: 0
  1. popitem(): Removes and returns an arbitrary key-value pair from the dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.popitem())  # Output: ('c', 3)
  1. update(dictionary): Updates the dictionary with the key-value pairs from the specified dictionary.
vros.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {'d': 4, 'e': 5}
my_dict.update(new_dict)
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

In summary, Python provides a rich set of methods for manipulating dictionaries. These methods make it easy to add, remove, and modify the key-value pairs in a dictionary.


14. How to create directory in Python? Give example.

In Python, you can create a directory using the os module. The os module provides a method called mkdir() that you can use to create a directory.

Here is an example of how to create a directory in Python:

vros.py
import os
 
# specify the name of the directory to be created
directory_name = "my_directory"
 
# specify the path where you want to create the directory
path = "C:/vros/username/Desktop/"
 
# create a full path by joining the path and directory name
full_path = os.path.join(path, directory_name)
 
# create the directory
os.mkdir(full_path)
 
print("Directory created successfully!")

In this example, the os module is imported, and then the name of the directory to be created is specified as my_directory. The path where the directory should be created is specified as C:/vros/username/Desktop/. Then, the os.path.join() method is used to join the path and directory name together to create a full path to the new directory. Finally, the os.mkdir() method is used to create the directory.

Note that if the directory already exists, an error will be raised. You can use the os.path.exists() method to check if the directory already exists before creating it.


15. Write in brief about Dictionary in python. Write operations with suitable examples.

In Python, a dictionary is an unordered collection of key-value pairs, where each key is unique and maps to a corresponding value. It is also known as a hash map or associative array.

To create a dictionary, we use curly braces and separate the keys and values with a colon (:). For example:

vros.py
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}

We can also create a dictionary using the built-in dict() function, which takes key-value pairs as arguments. For example:

vros.py
my_dict = dict(apple=2, banana=3, orange=4)

Once we have a dictionary, we can perform various operations on it:

  1. Accessing values using keys:

We can access the value associated with a key using square brackets [] and the key name. For example:

vros.py
print(my_dict['apple'])   # Output: 2
  1. Updating values:

We can update the value associated with a key using square brackets [] and the key name. For example:

vros.py
my_dict['banana'] = 5
print(my_dict)   # Output: {'apple': 2, 'banana': 5, 'orange': 4}
  1. Adding new key-value pairs:

We can add new key-value pairs using square brackets [] and a new key name. For example:

vros.py
my_dict['grape'] = 6
print(my_dict)   # Output: {'apple': 2, 'banana': 5, 'orange': 4, 'grape': 6}
  1. Deleting key-value pairs:

We can delete a key-value pair using the del keyword and the key name. For example:

vros.py
del my_dict['orange']
print(my_dict)   # Output: {'apple': 2, 'banana': 5, 'grape': 6}
  1. Looping through keys and values:

We can loop through the keys or values using the keys() or values() method. For example:

vros.py
for key in my_dict.keys():
    print(key)
 
for value in my_dict.values():
    print(value)

16. What is the significant difference between list and dictionary?

The main difference between a list and a dictionary in Python is that a list is an ordered collection of elements, while a dictionary is an unordered collection of key-value pairs.

In a list, the elements are indexed by their position, starting with 0. We can access, add or remove elements from a list using their index. For example:

vros.py
my_list = [1, 2, 3, 4, 5]
print(my_list[2])  # Output: 3
 
my_list.append(6)
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]
 
my_list.pop(3)
print(my_list)  # Output: [1, 2, 3, 5, 6]

In contrast, a dictionary is a collection of key-value pairs, where each key is unique and maps to a corresponding value. We can access, add or remove elements from a dictionary using their keys. For example:

vros.py
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}
print(my_dict['banana'])  # Output: 3
 
my_dict['grape'] = 6
print(my_dict)  # Output: {'apple': 2, 'banana': 3, 'orange': 4, 'grape': 6}
 
del my_dict['orange']
print(my_dict)  # Output: {'apple': 2, 'banana': 3, 'grape': 6}

In summary, the main differences between a list and a dictionary in Python are:

  • Lists are ordered collections of elements, while dictionaries are unordered collections of key-value pairs.
  • In a list, we access, add or remove elements using their index, while in a dictionary we access, add or remove elements using their keys.

17. Compare List and Tuple.

In Python, both lists and tuples are used to store collections of elements. However, there are some key differences between them:

  1. Mutability: Lists are mutable, which means their contents can be modified after creation. Tuples, on the other hand, are immutable, which means they cannot be modified once they are created.
vros.py
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
 
my_list[0] = 4
print(my_list)  # Output: [4, 2, 3]
 
my_tuple[0] = 4  # Raises a TypeError
 
  • Syntax: Lists are defined using square brackets [], while tuples are defined using parentheses ().
vros.py
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
  1. Usage: Lists are commonly used when we need to add or remove elements from the collection during the program execution, or when the collection is of a variable length. Tuples are often used when we want to group related data together that should not be modified, or when we want to return multiple values from a function.
vros.py
# List example
my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
 
# Tuple example
def get_name_and_age():
    return ("John", 25)
  1. Performance: Tuples are generally faster than lists when accessing elements because they are immutable and their size cannot change. However, when it comes to adding or removing elements, lists are faster because they don't need to create a new object.
vros.py
# Accessing elements
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
 
start = time.time()
for i in range(1000000):
    x = my_list[2]
end = time.time()
print("List access time:", end - start)
 
start = time.time()
for i in range(1000000):
    x = my_tuple[2]
end = time.time()
print("Tuple access time:", end - start)

In summary, the main differences between lists and tuples in Python are that lists are mutable, defined with square brackets, used for variable-length collections and modifying the elements, while tuples are immutable, defined with parentheses, used for fixed-length collections, and grouping related data.


18. Explain sort() with an example.

In Python, the sort() method is used to sort the elements of a list in ascending order. The sort() method modifies the original list and returns None.

Here's an example of using the sort() method:

vros.py
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

In this example, we have an unsorted list of integers. We call the sort() method on this list, which sorts the list in ascending order. After the sort() method is called, we print the sorted list.

By default, the sort() method sorts the list in ascending order. If we want to sort the list in descending order, we can pass the reverse=True parameter to the sort() method, like this:

vros.py
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

In this example, we pass the reverse=True parameter to the sort() method, which sorts the list in descending order. After the sort() method is called, we print the sorted list.


19. How append() and extend() are different with reference to list in Python?

In Python, both append() and extend() are methods used to add elements to a list. However, they differ in how they add the elements.

append() method adds a single element to the end of the list. The element can be of any type, including another list.

Here's an example of using append() method:

vros.py
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]
 
my_list.append([5, 6])
print(my_list)  # Output: [1, 2, 3, 4, [5, 6]]

In the first example, we use the append() method to add a single integer element to the end of the list. In the second example, we use the append() method to add a list as an element to the end of the list.

extend() method, on the other hand, adds multiple elements to the end of the list. The elements must be iterable, such as another list or tuple.

Here's an example of using extend() method:

vros.py
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]
 
my_list.extend((7, 8, 9))
print(my_list)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In the first example, we use the extend() method to add a list of elements to the end of the list. In the second example, we use the extend() method to add a tuple of elements to the end of the list.

To summarize, append() adds a single element to the end of the list, while extend() adds multiple elements to the end of the list by iterating through them.


20. Write a program to input any two tuples and interchange the tuple variable.

Here's a Python program that takes two tuples as input and interchanges the tuple variable:

vros.py
# Taking input of the two tuples
tuple1 = tuple(input("Enter elements of first tuple separated by space: ").split())
tuple2 = tuple(input("Enter elements of second tuple separated by space: ").split())
 
# Printing the original tuples
print("Original Tuple 1:", tuple1)
print("Original Tuple 2:", tuple2)
 
# Interchanging the tuple variable
tuple1, tuple2 = tuple2, tuple1
 
# Printing the interchanged tuples
print("Interchanged Tuple 1:", tuple1)
print("Interchanged Tuple 2:", tuple2)

In this program, we take two tuples as input using the input() function and the split() method. Then we print the original tuples using the print() function.

Next, we interchange the tuple variables using tuple packing and unpacking. Finally, we print the interchanged tuples using the print() function.


21. Write a Python program to multiply two matrices.

vros.py
# Taking input for first matrix
print("Enter the elements of the first matrix: ")
rows1 = int(input("Enter the number of rows: "))
cols1 = int(input("Enter the number of columns: "))
 
matrix1 = []
for i in range(rows1):
    row = list(map(int, input().split()))
    matrix1.append(row)
 
# Taking input for second matrix
print("Enter the elements of the second matrix: ")
rows2 = int(input("Enter the number of rows: "))
cols2 = int(input("Enter the number of columns: "))
 
matrix2 = []
for i in range(rows2):
    row = list(map(int, input().split()))
    matrix2.append(row)
 
# Matrix multiplication
if cols1 != rows2:
    print("Matrices cannot be multiplied")
else:
    result_matrix = []
    for i in range(rows1):
        row = []
        for j in range(cols2):
            sum = 0
            for k in range(rows2):
                sum += matrix1[i][k] * matrix2[k][j]
            row.append(sum)
        result_matrix.append(row)
 
    # Printing the result
    print("Resultant matrix:")
    for row in result_matrix:
        print(row)

In this program, we take input for two matrices using the input() function and the split() method. Then we perform matrix multiplication using three nested loops. The outer two loops iterate through each row and column of the resultant matrix, and the innermost loop calculates the dot product of the corresponding row of the first matrix and column of the second matrix.

If the number of columns of the first matrix is not equal to the number of rows of the second matrix, we cannot perform matrix multiplication, and we print an error message. Otherwise, we create a new matrix to store the result and print it using the print() function.


22. Write a Python code to get the following dictionary as output:{1:1,3:9,5:25,7:49,9,81}

Here's the Python code to create the dictionary with keys from 1 to 9, and values as the squares of the keys for odd keys:

vros.py
my_dict = {}
for i in range(1, 10):
    if i % 2 == 1:
        my_dict[i] = i**2
 
print(my_dict)

Output:

vros.py
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

In this code, we create an empty dictionary my_dict. Then, we use a for loop to iterate through the range of values from 1 to 9. For each odd number, we add a key-value pair to the dictionary, where the key is the number itself and the value is the square of the number. Finally, we print the resulting dictionary.


23. Write the output for the following:

  1. >>>a=[1,2,3]

>>>b=[4,5,6]

>>>c=a+b

  1. >>>[1,2,3]*3
  2. >>>t=[’a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

>>>t[1:3]=[’x’, ‘y’]

>>>print t

  1. When we run the code:
vros.py
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)

Output: [1, 2, 3, 4, 5, 6]

In this code, we create two lists a and b with three integers each. We then use the + operator to concatenate the two lists and assign the result to c. Finally, we print the resulting list c, which contains all six integers from a and b.

  1. When we run the code:
vros.py
[1,2,3]*3

Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

In this code, we create a list with three integers [1,2,3] and use the * operator to multiply the list by 3. The resulting list contains three copies of the original list, concatenated together.

  1. When we run the code:
vros.py
t=['a', 'b', 'c', 'd', 'e', 'f']
t[1:3] = ['x', 'y']
print(t)

Output: ['a', 'x', 'y', 'd', 'e', 'f']

In this code, we create a list t with six elements. We then use slicing to access the second and third elements of the list (i.e., 'b' and 'c') and replace them with the list ['x', 'y']. The resulting list t has elements ['a', 'x', 'y', 'd', 'e', 'f'].


24. Give the output of Python code:

str=”Maharashtra State Board of Technical Education”

print(x[15:1])

print(x[-10:-1:2])

The given code contains an error in the variable name used. The variable is defined as str, which is a keyword in Python. We should not use built-in keywords as variable names.

Here is the corrected code:

vros.py
x = 'Maharashtra State Board of Technical Education'
print(x[15:1])  # Empty string because the start index is greater than the end index
print(x[-10:-1:2])  # 'clgni'

Output:

vros.py
''
clgni

In the first print statement, we use slicing to extract a substring from the 15th to the 1st index of the string x. However, since the start index is greater than the end index, an empty string is returned.

In the second print statement, we use slicing to extract a substring from the second last to the tenth last index of the string x, skipping every second character. The resulting substring is 'clgni'.


25. Give the output of Python code:

t=(1,2,3,(4,)[5,6])

print(t[3])

t[4][0]=7

print(t)

The given code has a syntax error in the tuple definition. The expression (4,) creates a tuple with a single element, which is the integer 4. However, the expression [5,6] creates a list with two elements, which cannot be combined with a tuple. We cannot create a tuple with a mix of types like this.

Here is a corrected version of the code:

vros.py
t = (1, 2, 3, (4,), [5, 6])
print(t[3])  # (4,)
t[4][0] = 7
print(t)  # (1, 2, 3, (4,), [7, 6])

Output:

vros.py
(4,)
(1, 2, 3, (4,), [7, 6])

In the first print statement, we access the element at index 3 of the tuple t, which is the tuple (4,).

In the second line, we try to change the first element of the list at index 4 of the tuple t from 5 to 7. Since lists are mutable, this assignment modifies the list in place.

In the final print statement, we see the modified tuple, where the list at index 4 now contains the values [7, 6]. Note that we cannot modify the tuple itself because tuples are immutable. However, we can modify mutable objects contained within a tuple, such as lists.


26. Write the output for the following if the variable fruit=’banana’:

>>>fruit[:3] o/p ‘ban’

>>>fruit[3:] o/p ‘ana’

>>>fruit[3:3] o/p ‘ ’

>>>fruit[:] o/p ‘banana’

If the variable fruit is defined as fruit='banana', then the output of the given expressions would be as follows:

vros.py
fruit[:3]    # Output: 'ban'
fruit[3:]    # Output: 'ana'
fruit[3:3]   # Output: ''
fruit[:]     # Output: 'banana'

In the first expression, fruit[:3], we use slicing to extract a substring of fruit from the beginning up to, but not including, the third character. This returns the string 'ban'.

In the second expression, fruit[3:], we use slicing to extract a substring of fruit starting from the fourth character to the end of the string. This returns the string 'ana'.

In the third expression, fruit[3:3], we use slicing to extract a substring of fruit starting from the fourth character up to, but not including, the fourth character. Since the start and end indices are the same, this returns an empty string.

In the fourth expression, fruit[:], we use slicing to extract the entire string fruit. Since the start and end indices are omitted, this returns a copy of the original string with no modifications, i.e., 'banana'.


27. Write is string? How to create it? Enlist various operations on strings.

A string is a sequence of characters, enclosed within quotes, in Python. It is one of the most commonly used data types in programming.

To create a string in Python, you can simply enclose a sequence of characters in either single quotes (') or double quotes ("). For example:

vros.py
my_string = 'Hello, World!'
another_string = "This is another string."

Once a string is created, there are various operations that can be performed on it. Here are some common string operations in Python:

  1. Concatenation: The + operator can be used to concatenate two strings together. For example:

    vros.py
    str1 = "Hello"
    str2 = "World"
    str3 = str1 + " " + str2
    print(str3)  # Output: "Hello World"
  2. Slicing: Substrings of a string can be extracted using slicing. The syntax for slicing is string[start:end:step]. For example:

    vros.py
    my_string = "abcdefghij"
    print(my_string[2:5])  # Output: "cde"
  3. Length: The len() function can be used to find the length of a string. For example:

    vros.py
    my_string = "Hello, World!"
    print(len(my_string))  # Output: 13
  4. Reversing a string: You can reverse a string using slicing with a negative step. For example:

    vros.py
    my_string = "abcdef"
    reversed_string = my_string[::-1]
    print(reversed_string)  # Output: "fedcba"
  5. Counting occurrences: The count() method can be used to count the number of occurrences of a substring within a string. For example:

    vros.py
    my_string = "Hello, World!"
    num_l = my_string.count('l')
    print(num_l)  # Output: 3
  6. Finding substrings: The find() and index() methods can be used to find the position of a substring within a string. For example:

    vros.py
    my_string = "Hello, World!"
    pos = my_string.find("World")
    print(pos)  # Output: 7
     
    pos = my_string.index("World")
    print(pos)  # Output: 7
  7. Converting case: The upper() and lower() methods can be used to convert a string to all uppercase or all lowercase letters, respectively. For example:

    vros.py
    my_string = "Hello, World!"
    uppercase_string = my_string.upper()
    print(uppercase_string)  # Output: "HELLO, WORLD!"
     
    lowercase_string = my_string.lower()
    print(lowercase_string)  # Output: "hello, world!"

These are just a few examples of the operations that can be performed on strings in Python. There are many more methods and functions available in the Python string library.