PYTHON M3 (1)
PYTHON M3 (1)
1(A)
In Python, a list is a collection of items that are ordered and mutable
(modifiable). Each item in a list is identified by its index, which is a numerical
value starting from 0 for the first item, 1 for the second item, and so on.
python
Copy code
my_list = [10, 20, 30, 40, 50]
In this list, my_list[0] would return 10 because 10 is the item at index 0.
List Indexing
List indexing refers to accessing individual elements of a list using their index.
Indexing in Python lists starts from 0 and goes up to len(list) - 1. Negative
indexing is also allowed, where -1 refers to the last element, -2 refers to the
second last element, and so on.
Example:
python
Copy code
my_list = [10, 20, 30, 40, 50]
Syntax: list[start:end:step]
python
Copy code
my_list = [10, 20, 30, 40, 50]
1(B)
Here's an explanation of each of the mentioned list methods with suitable examples:
1. append()
The append() method adds an element to the end of the list.
Example:
python
Copy code
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2. extend()
The extend() method extends the list by adding all elements from another list to
the end of the current list.
Example:
python
Copy code
my_list = [1, 2, 3]
another_list = [4, 5, 6]
my_list.extend(another_list)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
3. sort()
The sort() method sorts the list in ascending order. It modifies the original list
and does not return a new list.
Example:
python
Copy code
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
You can also sort in descending order by passing reverse=True as an argument:
python
Copy code
my_list.sort(reverse=True)
print(my_list) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]
4. count()
The count() method returns the number of occurrences of a specified element in the
list.
Example:
python
Copy code
my_list = [1, 2, 2, 3, 3, 3]
count_of_3 = my_list.count(3)
print(count_of_3) # Output: 3
5. pop()
The pop() method removes and returns the element at the specified index (default is
the last element).
Example:
python
Copy code
my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop()
print(popped_element) # Output: 5
print(my_list) # Output: [1, 2, 3, 4]
You can also specify the index to remove a specific element:
python
Copy code
element_at_index_2 = my_list.pop(2)
print(element_at_index_2) # Output: 3
print(my_list) # Output: [1, 2, 4]
These methods are useful for manipulating and working with lists in Python.
2(A)
A tuple in Python is similar to a list, but it is immutable, meaning its elements
cannot be changed once it is created. Tuples are created using parentheses ()
instead of square brackets [].
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
Differences between tuple and list:
Mutability:
Lists are mutable, meaning you can change, add, or remove elements after the list
is created.
Tuples are immutable, so once a tuple is created, you cannot change its elements.
Syntax:
Lists are defined using square brackets [], while tuples are defined using
parentheses ().
Performance:
Tuples are generally more memory efficient and faster than lists, especially for
simple operations.
Use cases:
Lists are used when you need a collection of items that can be modified, such as a
list of tasks, items in a shopping cart, etc.
Tuples are used when you want to ensure that the data cannot be changed
accidentally, such as coordinates, dimensions, or any other data that should remain
constant.
Methods:
Lists have more built-in methods for adding, removing, and modifying elements, such
as append(), extend(), insert(), remove(), pop(), and clear().
Tuples have fewer methods since they are immutable, but they do have methods like
count() and index().
Iteration:
Both tuples and lists can be iterated over using loops, but since tuples are
immutable, they are safer to use in situations where the data should not be
modified accidentally.
In summary, tuples are used when you want to ensure that the data remains constant,
while lists are used when you need a collection of items that can be modified.
2(B)
1. get(key[, default])
The get() method returns the value for the specified key in the dictionary. If the
key is not found, it returns the default value (which defaults to None).
Example:
python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get('b')
print(value) # Output: 2
Example:
python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
items = my_dict.items()
print(items) # Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
Example:
python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])
Example:
python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = my_dict.values()
print(values) # Output: dict_values([1, 2, 3])
3(A)
Lists in Python are mutable, which means that you can change their elements after
they are created. This mutability allows you to modify, add, or remove elements
from a list. Here's an example to illustrate this:
python
Copy code
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
3(B)
In Python, tuples are created using parentheses () and can contain any number of
elements separated by commas. Tuples can also be created without using parentheses
by separating the elements with commas. There are several ways to create and access
tuples:
Creating Tuples:
Using Parentheses:
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
Without Parentheses:
python
Copy code
my_tuple = 1, 2, 3, 4, 5
Creating an Empty Tuple:
python
Copy code
empty_tuple = ()
Creating a Tuple with a Single Element (Note the comma at the end):
python
Copy code
single_element_tuple = (1,)
Accessing Tuples:
Tuples can be accessed using indexing and slicing, similar to lists.
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
# Slicing
print(my_tuple[1:4]) # Output: (2, 3, 4)
# Negative indexing
print(my_tuple[-1]) # Output: 5
Immutable Nature:
Unlike lists, tuples are immutable, which means you cannot change the elements of a
tuple after it is created. However, you can create a new tuple with the desired
elements.
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
4(A)
Sure, let's discuss both list and dictionary data structures in Python with
examples:
List:
A list in Python is a collection of items that are ordered and mutable. Lists are
created using square brackets [] and can contain elements of different data types.
Example:
python
Copy code
my_list = [1, 2, 3, 4, 5]
Properties of Lists:
Ordered: Items in a list are ordered and can be accessed by their index.
Mutable: You can change, add, or remove elements in a list.
Example of List Manipulation:
python
Copy code
# Changing an element
my_list[2] = 10
# Appending an element
my_list.append(6)
# Removing an element
my_list.remove(2)
Example:
python
Copy code
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Properties of Dictionaries:
Unordered: Items in a dictionary are not ordered. They are stored and accessed by
their keys.
Mutable: You can change the value associated with a key, add new key-value pairs,
or remove existing key-value pairs.
Example of Dictionary Manipulation:
python
Copy code
# Changing the value associated with a key
my_dict['age'] = 31
1. Definition:
List: A list is a collection of items that are ordered and mutable.
Dictionary: A dictionary is a collection of key-value pairs that are unordered and
mutable.
2. Syntax:
List: Defined using square brackets [].
Dictionary: Defined using curly braces {} with key-value pairs separated by
colons :.
3. Accessing Elements:
List: Elements are accessed by their index, starting from 0.
Dictionary: Elements are accessed by their keys.
4. Mutability:
List: Mutable; elements can be changed, added, or removed.
Dictionary: Mutable; values associated with keys can be changed, new key-value
pairs can be added, and existing key-value pairs can be removed.
5. Ordering:
List: Ordered; maintains the order of elements as they are inserted.
Dictionary: Unordered; the order of key-value pairs is not guaranteed.
6. Use Cases:
List: Used for storing collections of items where the order matters and elements
may need to be modified.
Dictionary: Used for storing key-value mappings where each value is accessed by a
unique key.
7. Iteration:
List: Iterated over using indexes or using a loop like for item in my_list:.
Dictionary: Iterated over using keys, values, or items (key-value pairs) using
methods like keys(), values(), or items().
8. Memory Efficiency:
List: Typically consumes more memory compared to dictionaries, especially for large
collections.
Dictionary: Generally more memory efficient, especially for large collections, due
to its hash table implementation.
9. Examples:
python
Copy code
# List
my_list = [1, 2, 3, 4, 5]
# Dictionary
my_dict = {'name': 'Alice', 'age': 30, 'city': 'London'}
In summary, lists are suitable for ordered collections of items that may need to be
modified, while dictionaries are suitable for key-value mappings where fast lookup
by key is important. The choice between them depends on the specific requirements
of the program.
5
def rotate_list(lst, pos):
"""
Rotate the list around the given position.
Args:
- lst: The list to rotate.
- pos: The position around which to rotate the list.
Returns:
- rotated_lst: The rotated list.
"""
# Calculate the pivot index
pivot = pos % len(lst)
def main():
# Input list
my_list = [1, 2, 3, 4, 5]
if __name__ == "__main__":
main()
6
def interchange_digits(num):
"""
Interchange the digits of the given integer.
Args:
- num: The integer whose digits are to be interchanged.
Returns:
- interchanged_num: The integer with digits interchanged.
"""
# Convert the integer to a string
num_str = str(num)
return interchanged_num
def main():
# Input integer
num = int(input("Enter an integer: "))
if __name__ == "__main__":
main()
7
In Python, packing and unpacking of tuples refer to the process of assigning
multiple values to a single variable (packing) or extracting values from a tuple
into individual variables (unpacking). This is often used when working with
functions that return multiple values or when working with iterables like lists or
tuples.
Packing:
Packing is the process of combining multiple values into a tuple. You can pack
values by simply placing them inside parentheses ().
Example:
python
Copy code
my_tuple = 1, 2, 3
# This is equivalent to my_tuple = (1, 2, 3)
Unpacking:
Unpacking is the process of extracting values from a tuple into individual
variables. You can unpack a tuple by assigning it to multiple variables separated
by commas.
Example:
python
Copy code
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Using * for Unpacking:
You can use * to unpack a variable number of elements into a single variable. This
is useful when you have a tuple with a variable number of elements.
Example:
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
a, *rest, b = my_tuple
print(a) # Output: 1
print(b) # Output: 5
print(rest) # Output: [2, 3, 4]
Functions Returning Multiple Values:
Packing and unpacking are often used when working with functions that return
multiple values. For example:
python
Copy code
def get_coordinates():
return 10, 20, 30
x, y, z = get_coordinates()
print(x, y, z) # Output: 10 20 30
Packing and unpacking of tuples are powerful features in Python that allow you to
work with multiple values conveniently and efficiently.
In Python, sets are unordered collections of unique elements. Sets support several
methods for deleting elements, including remove() and pop().
(a) remove()
The remove() method removes a specified element from the set. If the element is not
found, it raises a KeyError.
Example:
python
Copy code
my_set = {1, 2, 3, 4, 5}
# Remove element 3
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
Example:
python
Copy code
my_set = {1, 2, 3, 4, 5}
9
Here's a Python program that demonstrates the add() and update() functions in sets:
python
Copy code
# Create a set
my_set = {1, 2, 3, 4, 5}
10)
Characteristics of tuples:
Ordered: Like lists, tuples maintain the order of elements, meaning the order in
which elements are inserted is preserved.
Immutable: Once a tuple is created, its elements cannot be changed. This makes
tuples suitable for representing fixed collections of items.
Heterogeneous Elements: Tuples can contain elements of different data types, such
as integers, strings, floats, and even other tuples.
Indexing and Slicing: Elements in a tuple can be accessed using indexing and
slicing, similar to lists. Indexing starts from 0, and negative indexing is also
supported.
Example of a tuple:
python
Copy code
my_tuple = (1, 'hello', 3.14, (4, 5))
In this example, my_tuple is a tuple containing an integer, a string, a float, and
another tuple.