PRACTICAL – 02: TO STUDY PYTHON
ARRAYS, LISTS, TUPLES, SETS AND
DICTIONARY.
Aim: To study python arrays, list, tuples, set, dictionary.
Q. What is an Array?
An array is a special variable, which can hold more than one value at
a time. If you have a list of items (a list of car names for example),
storing cars in single variables could look like this:
car1 = "Ford", car2 = "Volvo", car3 = "BMW"
However, what if you want to loop through the cars and find a
specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can
access the values by referring to an index number.
Array Methods: Python has built in methods that you can
use on lists.
Method Description
1) append() Adds an element at the end of the list
2) clear() Removes all the elements from the list
3) copy() Returns a copy of the list
4) count() Returns the number of elements with the specified value
Adds the elements of a list (or any iterable) to the end of
5) extend()
the current list
Returns the index of the first element with the specified
6) index()
value
7) insert() Adds an element at the specified position
8) pop() Removes the element at the specified position
9) remove() Removes the first item with the specified value
10) reverse() Reverses the order of the list
11) sort() Sorts the list
Python List:
This list is a most versatile datatype available in Python which can be written as a list of
comma separated values between square brackets.
Important thing about a list is that items in a list need not be of the same type.
Accessing Values in Lists:
To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
Updating Lists:
You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and you can add elements in a list with the append() method.
Delete List Elements:
To remove a list element, you can use either the del statement if you know exactly which
element you are deleting or the remove() method if you do not know.
Basics List Operations:
Indexing, Slicing and Matrices:
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Python Expressions:
Python
Result Description
Expression
L[2] SPAM! Offset starts at zero
Negative index counts from
L[-2] Spam
right
['Spam',
L[1:1] Slicing fetches sections
'SPAM']
Built-in List Functions:-
Sr.
Function Description
No
cmp(list1, Compares elements of both
1
list2) lists
Gives the total length of the
2 len(list)
list
Returns item with maximum
3 max(list)
value
4 min(list) Returns item with minimum
Sr.
Function Description
No
value
5 list(seq) Converts a tuple into a list
Python Tuple:
of tuple is a sequence of immutable Python objects Tuples are
sequences, Just like list the tuples tuples cannot be charged unlike best
and tuples ute parenthese, whereas lists use square bracket Geating a
tuple is a simple as putting different comma-separated values
Opticanally you can put these comma separated values betiveer
parenthese.
Accessing Valued in Tuples:
To access value in tuples use the square brackets for slicing along
with the index or indices to obtain value available at that index..
Updating Tuples:
Tuples are immutable which means you cannot update or change the
values of tuple elements. You are able to take portions of existing
tuples to create new tuples as the following.
Delete Tuple Elements:
Removing individual tuple elements is not possible There is, of course
nothing wrong with putting together another tuple with the undesired
elements discarded. To explicitly remove an entire tuple, just del
statement.
BASIC TUPLE OPERATIONS:
Tuples are sequences, Indexing and slicing work the same way for
Tuples as they do for string tuples respond to the ‘+’ and ‘*’ operators
much like strings; they mean concentration and repetition here too
except that the result is a new tuple.
L=(‘spam’, ‘spam’, ‘SPAM’)
Python Result Description
Expression
L[2] 'SPAM' Offsets start at zero: Accesses the third
element (index 2).
L[-2] 'Spam' Negative indexing: Counts from the
right. -1 is the last, -2 is the second to last.
L[1:] ['Spam', Slicing fetches section: Returns all
'SPAM']* elements from index 1 to the end
Python Sets:
A set is a collection which is unordered and unindexed. In Python sets
are written with curly brackets.
Sr. Method Description
No.
1 [Link](obj) Appends object obj to the list.
2 [Link](obj) Returns count of how many times obj occurs
in the list.
3 [Link](seq) Appends the contents of sequence seq to the
list.
4 [Link](obj) Returns the lowest index in the list
where obj appears.
5 [Link](index, Inserts object obj into list at given index.
obj)
6 [Link](obj = list[- Removes and returns last element or specified
1]) element from list.
7 [Link](obj) Removes object obj from the list.
8 [Link]() Reverses the elements of the list in place.
9 [Link](func) Sorts the list elements; uses comparison
function if given.
Access items:
You cannot access items in a set by referring to an index, since sets
are unordered and have no index. But you can loop through the set
items using a for loop, or check if a specified value is present in a set
by using the in keyword.
Change items:
Once a set is created, you cannot change its items, but you can add
new items.
Add items:
To add one item to a set, use the add() method.
To add more than one item to a set, use the update() method.
Get length of a set:
To determine how many items a set has, use the len() method.
Remove item:
To remove an item in a set, use the remove() or the discard() method.
You can also use the pop() method to remove an item, but this method
will remove the last element. Sets are unordered, so you will not
know what item gets removed.
Dictionary:
A dictionary is a collection which is unordered, changeable, and
indexed. In Python, dictionaries are written with curly brackets, and
they have keys and values.
Accessing items:
You can access the items of a dictionary by referring to its key name,
inside square brackets.
Conclusion:
Thus we have studied Python arrays, list, tuple, set, dictionary.
2.1 “Tasks manager” (to do list)
def to_do():
tasks = []
while True:
print("1. add the task")
print("2. show the task")
print("3. remove the task")
print("4. exit the program")
choice = input("enter the choice: ")
if choice == "1":
task = input("enter the task: ")
[Link](task)
print("The task is added")
elif choice == "2":
print("Tasks:")
if len(tasks) == 0:
print("No tasks available")
else:
for task in tasks:
print(" - " + task)
elif choice == "3":
task = input("what task to remove: ")
if task in tasks:
[Link](task)
print("The task is removed")
else:
print("Task not found")
elif choice == "4":
print("Exit the program")
break
else:
print("Invalid option")
to_do()
OUTPUT:
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 1
enter the task: pen
The task is added
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 2
Tasks:
- pen
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 1
enter the task: table
The task is added
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 1
enter the task: bottle
The task is added
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 2
Tasks:
- pen
- table
- bottle
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 3
what task to remove: pen
The task is removed
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 2
Tasks:
- table
- bottle
1. add the task
2. show the task
3. remove the task
4. exit the program
enter the choice: 4
Exit the program
2.2 “Student Records Manager using
Dictionary”
students = {}
def add_student():
name = input("Enter student name: ")
grade = input("Enter grade: ")
attendance = int(input("Enter attendance percentage: "))
students[name] = {
"grade": grade,
"attendance": attendance
}
print("Student added successfully.")
def update_student():
name = input("Enter student name to update: ")
if name in students:
grade = input("Enter new grade: ")
attendance = int(input("Enter new attendance percentage: "))
students[name]["grade"] = grade
students[name]["attendance"] = attendance
print("Student record updated.")
else:
print("Student not found.")
def display_students():
if not students:
print("No student records found.")
else:
print("\nStudent Records:")
for name, details in [Link]():
print("Name:", name)
print("Grade:", details["grade"])
print("Attendance:", details["attendance"], "%")
print("---------------------")
while True:
print("\nStudent Records Manager")
print("1. Add Student")
print("2. Update Student")
print("3. Display Students")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
add_student()
elif choice == "2":
update_student()
elif choice == "3":
display_students()
elif choice == "4":
print("Exiting program...")
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Tejas
Enter grade: A
Enter attendance percentage: 95
Student added successfully.
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Rohit
Enter grade: A
Enter attendance percentage: 92
Student added successfully.
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Sai
Enter grade: A
Enter attendance percentage: 90
Student added successfully.
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Darshil
Enter grade: A
Enter attendance percentage: 90
Student added successfully.
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Anish
Enter grade: A
Enter attendance percentage: 90
Student added successfully.
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 3
Student Records:
Name: Tejas
Grade: A
Attendance: 95 %
---------------------
Name: Rohit
Grade: A
Attendance: 92 %
---------------------
Name: Sai
Grade: A
Attendance: 90 %
---------------------
Name: Darshil
Grade: A
Attendance: 90 %
---------------------
Name: Anish
Grade: A
Attendance: 90 %
---------------------
Student Records Manager
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 4
Exiting program...