0% found this document useful (0 votes)
2 views12 pages

PYTHON M3 (1)

The document provides an overview of Python data structures including lists, tuples, and dictionaries, detailing their properties, methods, and differences. It explains list operations such as indexing, slicing, and various methods like append() and sort(), as well as tuple immutability and dictionary key-value pair management. Additionally, it includes examples of manipulating these data structures and compares lists and dictionaries based on their characteristics.

Uploaded by

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

PYTHON M3 (1)

The document provides an overview of Python data structures including lists, tuples, and dictionaries, detailing their properties, methods, and differences. It explains list operations such as indexing, slicing, and various methods like append() and sort(), as well as tuple immutability and dictionary key-value pair management. Additionally, it includes examples of manipulating these data structures and compares lists and dictionaries based on their characteristics.

Uploaded by

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

MODULE (3)

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.

Here's a simple example of a list:

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]

# Accessing the first element


first_element = my_list[0] # 10

# Accessing the last element using negative indexing


last_element = my_list[-1] # 50
List Slicing
List slicing is a technique to extract a subsequence of elements from a list. It
allows you to specify a range of indices and extract the elements from that range.

Syntax: list[start:end:step]

start is the starting index of the slice (inclusive).


end is the ending index of the slice (exclusive).
step is the step size (default is 1).
Example:

python
Copy code
my_list = [10, 20, 30, 40, 50]

# Slicing from index 1 to 3 (exclusive)


sub_list = my_list[1:3] # [20, 30]

# Slicing from index 0 to 4 with step 2


sub_list_step = my_list[0:4:2] # [10, 30]
List slicing returns a new list containing the specified elements from the original
list. If start or end is not provided, it defaults to the beginning or end of the
list, respectively.

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 [].

Here's how you can define a tuple:

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)

In Python, dictionaries are used to store key-value pairs. Here's an explanation of


the dictionary methods get(), items(), keys(), and values():

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

# Providing a default value


value = my_dict.get('d', 'Key not found')
print(value) # Output: 'Key not found'
2. items()
The items() method returns a view object that displays a list of a dictionary's
key-value tuple pairs.

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

# Iterating over key-value pairs


for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
3. keys()
The keys() method returns a view object that displays a list of all the keys in the
dictionary.

Example:

python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])

# Iterating over keys


for key in my_dict.keys():
print(key)
4. values()
The values() method returns a view object that displays a list of all the values in
the dictionary.

Example:
python
Copy code
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = my_dict.values()
print(values) # Output: dict_values([1, 2, 3])

# Iterating over values


for value in my_dict.values():
print(value)
These methods are useful for working with dictionaries in Python and provide ways
to access and manipulate the keys and values in a dictionary.

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]

# Changing an element at a specific index


my_list[2] = 10
print(my_list) # Output: [1, 2, 10, 4, 5]

# Appending an element to the end of the list


my_list.append(6)
print(my_list) # Output: [1, 2, 10, 4, 5, 6]

# Removing an element by value


my_list.remove(2)
print(my_list) # Output: [1, 10, 4, 5, 6]

# Removing an element by index


del my_list[0]
print(my_list) # Output: [10, 4, 5, 6]
In the above example, you can see that we can change, add, and remove elements from
the list. This is possible because lists are mutable in Python.

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)

# Accessing individual elements


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

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

# Attempting to change a tuple element will raise an error


my_tuple[0] = 10 # Raises TypeError: 'tuple' object does not support item
assignment

# Creating a new tuple with updated elements


new_tuple = my_tuple[:2] + (10,) + my_tuple[3:]
print(new_tuple) # Output: (1, 2, 10, 4, 5)
Tuples are commonly used to store related pieces of information that should not be
changed, such as coordinates, database records, or function arguments.

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)

print(my_list) # Output: [1, 10, 4, 5, 6]


Dictionary:
A dictionary in Python is a collection of key-value pairs. Dictionaries are created
using curly braces {} and each item in a dictionary is a key-value pair separated
by a colon :.

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

# Adding a new key-value pair


my_dict['gender'] = 'Male'

# Removing a key-value pair


del my_dict['city']

print(my_dict) # Output: {'name': 'John', 'age': 31, 'gender': 'Male'}


Dictionaries are commonly used to store and manipulate data that can be represented
as key-value pairs, such as user profiles, configurations, or any mapping between
unique keys and values.
4(B)
Here's a comparison of lists and dictionaries in Python based on various aspects:

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)

# Rotate the list


rotated_lst = lst[pivot:] + lst[:pivot]
return rotated_lst

def main():
# Input list
my_list = [1, 2, 3, 4, 5]

# Input position to rotate around


position = int(input("Enter the position to rotate around: "))

# Rotate the list


rotated_list = rotate_list(my_list, position)

# Display the rotated list


print("Rotated List:", rotated_list)

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)

# Interchange the digits


interchanged_num_str = num_str[-1] + num_str[1:-1] + num_str[0]

# Convert the string back to an integer


interchanged_num = int(interchanged_num_str)

return interchanged_num

def main():
# Input integer
num = int(input("Enter an integer: "))

# Interchange the digits


interchanged_num = interchange_digits(num)

# Display the integer with digits interchanged


print("Integer with digits interchanged:", interchanged_num)

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}

# Try to remove a non-existent element


try:
my_set.remove(6)
except KeyError as e:
print("KeyError:", e) # Output: KeyError: 6
(b) pop()
The pop() method removes and returns an arbitrary element from the set. Since sets
are unordered, there is no guarantee which element will be removed. If the set is
empty, it raises a KeyError.

Example:

python
Copy code
my_set = {1, 2, 3, 4, 5}

# Remove and return an arbitrary element


popped_element = my_set.pop()
print(popped_element) # Output: 1
print(my_set) # Output: {2, 3, 4, 5}

# Try to pop from an empty set


empty_set = set()
try:
popped_element = empty_set.pop()
except KeyError as e:
print("KeyError:", e) # Output: KeyError: 'pop from an empty set'
Both remove() and pop() are useful for removing elements from sets, with remove()
allowing you to specify the element to remove, and pop() providing a way to remove
an arbitrary element.

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}

# Demonstrate the add() function


my_set.add(6)
print("After adding 6:", my_set)
# Demonstrate the update() function
my_set.update([7, 8, 9])
print("After updating with [7, 8, 9]:", my_set)

# Demonstrate update() with another set


another_set = {10, 11, 12}
my_set.update(another_set)
print("After updating with another set:", my_set)
This program first creates a set my_set with elements 1, 2, 3, 4, 5. It then
demonstrates the add() function by adding the element 6 to the set. Next, it
demonstrates the update() function by updating the set with the elements [7, 8, 9].
Finally, it demonstrates the update() function again, this time updating the set
with another set another_set containing elements 10, 11, 12.

10)

A tuple in Python is an ordered collection of elements, similar to a list. However,


tuples are immutable, meaning they cannot be changed (elements cannot be added,
removed, or modified) after they are created. Tuples are defined using parentheses
() and can contain elements of different data types.

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.

You might also like