Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

UNIT 3

LIST, TUPLES AND DICTIONARIES

List, List Operations Built in List functions, Tuple, Tuple Operations, Dictionary, Operations in
Dictionary, Built in Dictionary Methods.

Practice Programs:

1. A hospital has received a set of lab reports. Totally five tests are conducted in the lab and
the report is prepared in such a way that the ‘nth’ number correspond to value of test n. Given the
details of a test made for a patient, write an algorithm and the subsequent Python program to
print if the test result is normal or not normal by referring the values in Table 1. Since the value is
sensitive, provide a mechanism so that the values do not get altered.
Name of the Minimum Maximum
Test value value
Test1 20 30
Test2 35.5 40
Test3 12 15
Test4 120 150
Test5 80 120

2. An University has published the results of the term end examination conducted in April.
List of failures in physics, mathematics, chemistry and computer science is available. Write a
program to find the number of failures in the examination. This includes the count of failures in
one or more subjects.
3. Write a program to maintain a telephone directory of the employees of an organization. If
the employee has more than one number store all the numbers. Write a program to print the
mobile numbers given full or part of the name of the employee. Eg: Given name of the employee
as ‘John’ the program must print phone numbers of ‘John Paul’ and ‘Michel John’.

List in Python:

In Python, a list is a versatile and fundamental data structure that allows you to store and
manipulate a collection of items. Lists are mutable, meaning you can modify their
elements by adding, removing, or changing values. They are defined using square
brackets `[]` and can contain elements of different data types, such as integers, floats,
strings, or even other lists.

Here's a brief introduction to working with lists in Python:

1. Creating a List:

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

2. Accessing Elements:
Elements in a list are accessed using zero-based indexing. For example:
print(my_list[0]) # Output: 1

3. Modifying Elements:
Lists are mutable, so you can change or update their elements:

my_list[2] = 10

4. Adding Elements:
You can append elements to the end of the list using the `append` method:

my_list.append(6)

5. Inserting Elements:
Insert an element at a specific index using the `insert` method:

my_list.insert(2, 7) # Inserts 7 at index 2

6. Removing Elements:
Remove an element by value using the `remove` method or by index using the `del`
statement:

my_list.remove(4) # Removes the first occurrence of 4


del my_list[1] # Removes the element at index 1

7. Slicing:
Extract sublists or slices using the slice notation:

sublist = my_list[1:4] # Extracts elements from index 1 to 3

8. List Concatenation:
Combine two lists using the `+` operator:

new_list = my_list + [8, 9, 10]

9. Length of a List:
Determine the number of elements in a list using the `len` function:

length = len(my_list)

Lists provide a powerful and flexible way to handle collections of data in Python, making
them a fundamental part of the language.
List Operations Built in List functions:

Python provides several built-in functions and methods for performing various operations
on lists. Here are some commonly used ones:

1. `len()` Function:
Returns the length (number of elements) of a list.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Output: 5

2. `append()` Method:
Adds an element to the end of the list.

my_list.append(6)

3. `insert()` Method:
Inserts an element at a specified position in the list.

my_list.insert(2, 7) # Inserts 7 at index 2

4. `remove()` Method:
Removes the first occurrence of a specified element from the list.

my_list.remove(4) # Removes the first occurrence of 4

5. `pop()` Method:
Removes and returns the element at a specified index (default is the last element).

popped_element = my_list.pop(2) # Removes and returns the element at index 2

6. `index()` Method:
Returns the index of the first occurrence of a specified element.

index = my_list.index(3) # Returns the index of the first occurrence of 3

7. `count()` Method:
Returns the number of occurrences of a specified element in the list.

count = my_list.count(2) # Returns the number of occurrences of 2

8. `sort()` Method:
Sorts the elements of the list in ascending order (in-place).

my_list.sort()
9. `reverse()` Method:
Reverses the order of elements in the list (in-place).

my_list.reverse()

10. `copy()` Method:


Creates a shallow copy of the list.

new_list = my_list.copy()

11. `extend()` Method:


Extends the list by appending elements from another iterable.

another_list = [8, 9, 10]


my_list.extend(another_list)

These functions and methods provide a powerful set of tools for working with lists in
Python. They allow you to manipulate, modify, and retrieve information from lists
efficiently.

Tuple in Python:

In Python, a tuple is an ordered, immutable collection of elements. This means that once a
tuple is created, its elements cannot be modified, added, or removed. Tuples are defined
using parentheses `()` and can contain elements of different data types, such as integers,
floats, strings, or even other tuples.

Here's a brief introduction to working with tuples in Python:

1. Creating a Tuple:

my_tuple = (1, 2, 3, 4, 5)

2. Accessing Elements:
Elements in a tuple are accessed using zero-based indexing, similar to lists:

print(my_tuple[0]) # Output: 1

3. Immutable Nature:
Tuples are immutable, meaning you cannot modify their elements once the tuple is
created. The following code would raise an error:

my_tuple[2] = 10 # Raises TypeError


4. Single-element Tuple:
If you want to create a tuple with a single element, you need to include a trailing comma:

single_element_tuple = (7,)

5. Tuple Packing and Unpacking:


Tuple packing involves creating a tuple with multiple elements. Tuple unpacking allows
you to assign the elements of a tuple to individual variables:

coordinates = (3, 4)
x, y = coordinates

6. Concatenation:
You can concatenate tuples using the `+` operator:

new_tuple = my_tuple + (6, 7, 8)

7. Length of a Tuple:
Determine the number of elements in a tuple using the `len` function:

length = len(my_tuple)

8. Nested Tuples:
Tuples can contain other tuples, creating nested structures:

nested_tuple = (1, (2, 3), 4)

Tuples are often used when the data should remain constant throughout the program
execution or when the order of elements matters, but their values should not be changed.
They provide a lightweight and efficient way to store and manage fixed collections of data.

Tuple Operations in Python:

Tuples in Python support various operations, although they are immutable


(unchangeable) once created. Here are some common tuple operations and methods:

1. Accessing Elements:
Elements in a tuple are accessed using zero-based indexing, similar to lists.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1

2. Tuple Packing and Unpacking:


Tuple packing involves creating a tuple with multiple elements. Tuple unpacking allows
you to assign the elements of a tuple to individual variables.

coordinates = (3, 4)
x, y = coordinates

3. Concatenation:
You can concatenate tuples using the `+` operator.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2

4. Repetition:
You can create a new tuple by repeating an existing tuple using the `*` operator.

repeated_tuple = (1, 2) * 3 # Output: (1, 2, 1, 2, 1, 2)

5. Length of a Tuple:
Determine the number of elements in a tuple using the `len` function.

my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)

6. Membership Test:
Check if an element is present in a tuple using the `in` operator.

my_tuple = (1, 2, 3, 4, 5) is_present = 3 in


my_tuple # Output: True

7. Index Method:
Find the index of the first occurrence of a specific element in the tuple.

my_tuple = (1, 2, 3, 4, 5)
index = my_tuple.index(3) # Output: 2

8. Count Method:
Count the number of occurrences of a specific element in the tuple.

my_tuple = (1, 2, 3, 2, 4, 2, 5) count


= my_tuple.count(2) # Output: 3
While tuples lack some of the flexibility of lists due to their immutability, they are useful for
situations where the data should remain constant or for representing fixed collections of
values.

Dictionary in Python:

In Python, a dictionary is a powerful and flexible data structure used to store and retrieve
key-value pairs. Dictionaries are also known as associative arrays or hash maps in other
programming languages. Unlike sequences (lists and tuples), dictionaries are unordered
collections, meaning they do not have a specific order for their elements. Dictionaries are
defined using curly braces `{}` and consist of key-value pairs separated by colons.

Here's a brief introduction to working with dictionaries in Python:

1. Creating a Dictionary:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

2. Accessing Values:
Values in a dictionary are accessed using their associated keys.

print(my_dict['name']) # Output: John

3. Adding and Modifying Entries:


You can add new key-value pairs or modify existing ones.

my_dict['occupation'] = 'Engineer' # Adding a new key-value pair


my_dict['age'] = 31 # Modifying the value for an existing key

4. Removing Entries:
Use the `del` statement to remove a key-value pair by key.

del my_dict['city']

5. Dictionary Methods:
- `keys()`: Returns a view of all the keys in the dictionary.
- `values()`: Returns a view of all the values in the dictionary. -
`items()`: Returns a view of all key-value pairs as tuples.

keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()

6. Dictionary Iteration:
You can iterate over the keys, values, or items in a dictionary using loops.
for key in my_dict:
print(key, my_dict[key])

# Or, using items() for both key and value


for key, value in my_dict.items():
print(key, value)

7. Checking Membership:
Use the `in` operator to check if a key is present in the dictionary.

if 'name' in my_dict: print('Key "name"


exists in the dictionary')

8. Dictionary Comprehension:
Similar to list comprehensions, you can create dictionaries in a concise way.

squares = {x: x2 for x in range(5)}

Dictionaries are highly versatile and efficient for tasks involving key-based data retrieval,
making them an essential part of Python programming. They are widely used for tasks
such as representing configuration settings, storing data with unique identifiers, and more.

Operations in Dictionary:

Python dictionaries support various operations and methods for manipulating key-value
pairs. Here are some common operations you can perform with dictionaries:

1. Accessing Values:
Access values using keys.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


print(my_dict['name']) # Output: John

2. Adding and Modifying Entries:


Add new key-value pairs or modify existing ones.

my_dict['occupation'] = 'Engineer' # Adding a new key-value pair


my_dict['age'] = 31 # Modifying the value for an existing key

3. Removing Entries:
Remove a key-value pair by key using the `del` statement.

del my_dict['city']

4. Dictionary Methods:
- `keys()`: Returns a view of all the keys in the dictionary.
- `values()`: Returns a view of all the values in the dictionary.
- `items()`: Returns a view of all key-value pairs as tuples.

keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()

5. Dictionary Iteration:
Iterate over the keys, values, or items in a dictionary using loops.

for key in my_dict:


print(key, my_dict[key])

# Or, using items() for both key and value


for key, value in my_dict.items():
print(key, value)

6. Checking Membership:
Check if a key is present in the dictionary using the `in` operator.

if 'name' in my_dict:
print('Key "name" exists in the dictionary')

7. Dictionary Comprehension:
Create dictionaries in a concise way using dictionary comprehensions.

squares = {x: x2 for x in range(5)}

8. Updating a Dictionary:
Update a dictionary with elements from another dictionary or iterable.

new_data = {'city': 'San Francisco', 'gender': 'Male'}


my_dict.update(new_data)

9. Default Values with `get()`:


Retrieve a value with a default if the key is not present.

age = my_dict.get('age', 0) # If 'age' is not present, returns 0

10. Removing Items with `pop()`:


Remove and return the value for a specified key.

value = my_dict.pop('name')

11. Clearing a Dictionary:


Remove all items from the dictionary.
my_dict.clear()

These operations make dictionaries a versatile and powerful tool for managing and
manipulating key-value pairs in Python. They are commonly used for various tasks such
as representing data, configuration settings, and more.

Built in Dictionary Methods:

Python dictionaries come with a variety of built-in methods that allow you to perform
various operations on key-value pairs. Here are some commonly used dictionary
methods:

1. `clear()`:
Removes all items from the dictionary.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


my_dict.clear()

2. `copy()`:
Creates a shallow copy of the dictionary.

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


copied_dict = original_dict.copy()

3. `get(key, default)`:
Returns the value for the specified key. If the key is not present, it returns the default
value.

age = my_dict.get('age', 0) # If 'age' is not present, returns 0

4. `items()`:
Returns a view of all key-value pairs as tuples.

items_view = my_dict.items()

5. `keys()`:
Returns a view of all the keys in the dictionary.

keys_view = my_dict.keys()

6. `values()`:
Returns a view of all the values in the dictionary.

values_view = my_dict.values()
7. `pop(key, default)`:
Removes and returns the value for the specified key. If the key is not present, it returns
the default value.

name = my_dict.pop('name', 'Unknown')

8. `popitem()`:
Removes and returns the last key-value pair as a tuple.

last_item = my_dict.popitem()

9. `update(iterable)`:
Updates the dictionary with elements from another dictionary or iterable.

new_data = {'city': 'San Francisco', 'gender': 'Male'}


my_dict.update(new_data)

10. `setdefault(key, default)`:


Returns the value for the specified key. If the key is not present, inserts the key with the
default value.

age = my_dict.setdefault('age', 0)

11. `fromkeys(iterable, value)`:


Creates a new dictionary with keys from the iterable and values set to a specified value.

keys = ['name', 'age', 'city']


default_values = 'Unknown'
new_dict = dict.fromkeys(keys, default_values)

These built-in methods make it convenient to manipulate and interact with dictionaries in
Python. They provide a range of functionality for tasks such as copying dictionaries,
retrieving values, updating dictionaries, and more.

Practice Programs:

1. A hospital has received a set of lab reports. Totally five tests are conducted in the lab
and the report is prepared in such a way that the ‘n th’ number correspond to value of test n.
Given the details of a test made for a patient, write an algorithm and the subsequent
Python program to print if the test result is normal or not normal by referring the values in
Table 1. Since the value is sensitive, provide a mechanism so that the values do not get
altered.

Name of the Minimum Maximum


Test value value
Test1 20 30
Test2 35.5 40
Test3 12 15
Test4 120 150
Test5 80 120

Algorithm:
1. Create a dictionary (`normal_ranges`) to store the normal range values for each test.
2. Ask the user to input the test number and result.
3. Check if the test result is within the normal range using the dictionary.
4. Print whether the test result is normal or not.

Python Program:

# Step 1: Create a dictionary with normal range values for each test normal_ranges
={
'Test1': {'min': 20, 'max': 30},
'Test2': {'min': 35.5, 'max': 40},
'Test3': {'min': 12, 'max': 15},
'Test4': {'min': 120, 'max': 150},
'Test5': {'min': 80, 'max': 120}
}

# Step 2: Ask the user to input test name and result try:
test_name = input("Enter the name of the test (Test1 to Test5): ")
test_result = float(input("Enter the test result: ")) except ValueError:
print("Invalid input. Please enter a valid number.")

# Step 3: Check if the test result is within the normal range if


test_name in normal_ranges:
normal_range = normal_ranges[test_name]

if normal_range['min'] <= test_result <= normal_range['max']:


print("Test result is normal.")
else:
print("Test result is not normal.") else: print("Invalid test name.
Please enter a valid test name (Test1 to Test5).")

This program uses the test names as keys in the dictionary and ensures that the normal
range values are stored securely. It also handles user input validation to ensure that the
input is a valid number and a valid test name.

2. An University has published the results of the term end examination conducted in April.
List of failures in physics, mathematics, chemistry and computer science is available. Write
a program to find the number of failures in the examination. This includes the count of
failures in one or more subjects.
Python program:

def count_failures(*subjects):
"""
Count the number of students who failed in one or more subjects.
"""
total_failures = 0

for subject in subjects:


total_failures += len(subject)

return total_failures

# Example: List of failures in each subject physics_failures =


['student1', 'student2', 'student3'] math_failures = ['student2',
'student4', 'student5'] chemistry_failures = ['student3',
'student5', 'student6'] computer_science_failures = ['student1',
'student4', 'student6']

# Calculate the total number of failures


total_failures = count_failures(physics_failures, math_failures, chemistry_failures,
computer_science_failures)

# Print the result


print(f'Total number of failures: {total_failures}')

In this program:
- The `count_failures` function takes variable arguments for the lists of failures in each
subject.
- It iterates through each subject list and counts the number of failures.
- The example data includes lists of failures in physics, mathematics, chemistry, and
computer science.
- The total number of failures across all subjects is calculated and printed.

You can customize the example data or integrate this logic into your existing code,
depending on your specific requirements.

3. Write a program to maintain a telephone directory of the employees of an organization. If


the employee has more than one number store all the numbers. Write a program to print
the mobile numbers given full or part of the name of the employee. Eg: Given name of the
employee as ‘John’ the program must print phone numbers of ‘John Paul’ and ‘Michel
John’.

Python program:
class TelephoneDirectory:
def __init__(self):
self.directory = {}

def add_employee(self, name, numbers):


"""
Add an employee and their phone numbers to the directory.
"""
if name not in self.directory:
self.directory[name] = []
self.directory[name].extend(numbers)

def print_numbers_by_name(self, partial_name):


"""
Print mobile numbers based on the given full or partial name.
"""
matching_numbers = [] for name,
numbers in self.directory.items(): if
partial_name.lower() in name.lower():
matching_numbers.extend(numbers)

if matching_numbers: print(f"Mobile numbers for employees


with name '{partial_name}':") for number in matching_numbers:
print(number)
else:
print(f"No matching records found for '{partial_name}'.")

# Example usage:
telephone_directory = TelephoneDirectory()

# Adding employees and their numbers to the directory


telephone_directory.add_employee('John Paul', ['1234567890', '9876543210'])
telephone_directory.add_employee('Michael Johnson', ['8765432109'])
telephone_directory.add_employee('Alice Smith', ['5678901234', '9998887776'])
telephone_directory.add_employee('Michel John', ['1112223334'])

# Searching for mobile numbers by name


partial_name = 'John'
telephone_directory.print_numbers_by_name(partial_name)

In this program:
- The `TelephoneDirectory` class is used to store the employee names and their
corresponding mobile numbers.
- The `add_employee` method adds employees and their numbers to the
directory. - The `print_numbers_by_name` method searches for mobile numbers based
on the given full or partial name and prints the results.
You can customize the example data or modify the program based on your specific needs.

You might also like