Data Structure - List.pptx
Data Structure - List.pptx
ACTIVITIES
1. Understanding Data Structures
2. Understanding List
3. Demo 1 - Creating a Stationery List
4. Activity 1 - Creating a Subject List
LIST
5. Demo 2 - Positive & Negative Indexing
6. Activity 2 - Positive & Negative Indexing
7. Demo 3 - Slicing a List
8. Activity 3 - Slicing a List
9. Activity 4 - Grouping the Students
Understanding Data Structures
Data structure is a way of organizing and storing data in a
computer so that it can be accessed and modified efficiently.
List
Data
Set Mutable Immutable Tuple
Structure
Dictionary
Importance of Data Structures
Efficiency
1 Different structures offer faster access and manipulation for specific
types of data.
Organization
2
They keep your data well-organized and easy to understand.
Reusability
3 Many structures are commonly used across different programs,
saving time and effort.
Understanding List
● In Python, a list is a built-in data type that stores an ordered collection of
items/elements, that can be of any data type such as numbers, strings,
pictures, other lists, and more.
● Lists are defined using square brackets [ ] and the elements/items are
separated by commas.
● List elements/items are indexed, the first item has index[0], the second
item has index[1], and so on.
Code
1 fruits = [“apple”, “banana”, “mango”] #creating list
2 fruits[0] #accessing apple element
3 fruits[1]# accessing banana element
Characteristics of List
Lists maintain the order of elements as they are
inserted. This order remains unchanged unless
1. Ordered
deliberately rearranged or modified (delete or add)
by the programmer.
Code
1 # Creating a list of stationery items for school
2 stationery_items = ["Pencils", "Pens", "Notebooks", "Rulers"]
3 # Displaying the list of stationery items
4 print(stationery_items)
5 # Check the data type
6 print(type(stationery_items))
Output
['Pencils', 'Pens', 'Notebooks', 'Rulers']
<class 'list'>
Activity 1 - Creating a Subject List
Write a Python program that display a list of subjects learned by
Bhutanese students in class X.
Code
1 subject=["Dzongkha","English","Maths","ICT","Science"]
2 print(subject)
Output
['Dzongkha', 'English', 'Maths', 'ICT', 'Science']
Accessing Items of the List
● Accessing elements of a list in Python involves retrieving specific items
stored within the list by their index positions.
● Lists in Python are zero-indexed, meaning the index of the first element is
0, the second element is at index 1, and so on.
Types of
accessing
element
of List B. Slice
A. Index Operator
(:)
A. Accessing Elements of the List using Index
● Index refers to a sequential number or value that indicates the
position/location of an element within a data structure (list, tuple).
Indexes value starts from 0 for the first
element and value increases sequentially
for each subsequent element in the list.
2
Types of
Positive Indexing
indexing Negative Indexing
1
Indexes value starts from -1 for the last element
and values decreases sequentially moving
backward from the end of the list.
Positive and Negative Indexing
Code
1 school=[“Motithang HSS”, ”Zilukha MSS”, “Babesa MSS”]
Positive index 0 1 2
Negative index -3 -2 -1
Output
Second fruit (Positive Index): banana
Last fruit (Negative Index): kiwi
Second last fruit (Negative Index): grape
Activity 2 - Selecting a Bhutanese Festival
Write a Python program to create a list named festival containing Bhutanese
festivals: "Losar", "Tshechu", "Zhabdrung Kuchoe", "Thruebaab" and
"Dashain". Access the element "Tshechu" from the list using both positive and
negative indexing.
Code
1 festivals = ["Losar", "Tshechu", "Kuchoe", "Thruebaab", "Dashain"]
2 print(" Positive Index:",festivals[1])
3 print("Negative Index:", festivals[-4])
Output
Positive Index: Tshechu
Negative Index: Tshechu
B. Accessing Elements of the List using Slicing Operator
● In Python, the slicing operator (:) allows you to create a subsequence
(slice) of elements from a list based on specified indices or range of
indices.
syntax
variable_name[start : end : step] It refers to an incremental value. The default
value is 1.
It indicates the index where slice has to Start. The default value is 0.
It indicates the index where slice has to End. The default value is length of the List.
Demo 3 - Slicing a List of Numbers
Write a Python program that uses different slicing operators to display various
groups of numbers from the list numbers = [0,1,2,3,4,5,6,7,8,9].
Code
1 numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2 sliced_list_basic = numbers[2:6] # Basic slicing
3 sliced_list_start = numbers[:5] # Slicing without start index
4 sliced_list_end = numbers[5:] # Slicing without end index
5 sliced_list_step = numbers[1:9:2] # Slicing with a step of 2
6 sliced_list_negative = numbers[-5:-2] # Slicing using negative indices
7 print("Basic Slicing (numbers[2:6]):", sliced_list_basic)
8 print("Slicing without start index (numbers[:5]):", sliced_list_start)
9 print("Slicing without end index (numbers[5:]):", sliced_list_end)
Demo 3 - Slicing a List of Numbers
10 print("Slicing with step of 2 (numbers[1:9:2]):", sliced_list_step)
11 print("Slicing with negative indices (numbers[-5:-2]):",
sliced_list_negative)
12
Output
Basic Slicing (numbers[2:6]): [2, 3, 4, 5]
Slicing without start index (numbers[:5]): [0, 1, 2, 3, 4]
Slicing without end index (numbers[5:]): [5, 6, 7, 8, 9]
Slicing with step of 2 (numbers[1:9:2]): [1, 3, 5, 7]
Slicing with negative indices (numbers[-5:-2]): [5, 6, 7]
Activity 3 - Slicing a List of Places in Bhutan
Create a list name bhutan_places and initialize the list with names of six
Dzongkhags in Bhutan. Perform the following slicing operations.
1. Slice the list to extract elements from index 2 to 4.
2. Slice the list from index 2 till the end.
3. Perform slicing with a step of 3, extracting elements using every third
element.
4. Slice the list from the 5th element from the end up to the element just
before the last one.
Activity 3 - Slicing a List of Places in Bhutan
Code
1 bhutan_places = ["Thimphu", "Trashigang", "Punakha", "Samtse",
"Tsirang", "Haa"]#creating list
2 sliced_list = bhutan_places[2:5] #Slice from index 2 to 4
3 print("Output for Q1[2:5]:", sliced_list)
4 sliced_list_2 = bhutan_places[2:]#Slice from index 2 till end
5 print("Output for Q2[2::", sliced_list_2)
6 sliced_list_3 = bhutan_places[::3] # Slice with a step of 3
7 print("Output for Q3[::3]:", sliced_list_3)
8 sliced_list_4 = bhutan_places[-5:-1]
9 print("Output for Q4[-5:-1]:", sliced_list_4)
Activity 3 - Slicing a List of Places in Bhutan
Output
Output for Q1[2:5]: ['Punakha', 'Samtse', 'Tsirang']
Output for Q2[2:: ['Punakha', 'Samtse', 'Tsirang', 'Haa']
Output for Q3[::3]: ['Thimphu', 'Samtse']
Output for Q4[-5:-1}: ['Trashigang', 'Punakha', 'Samtse', 'Tsirang']
Activity 4 - Grouping Students for Presentation
Output
Group presentation:
student Group 1:['Tara', 'Sonam', 'Karma']
student Group 2:['Wangmo', 'Nima', 'Dorji']
ACTIVITIES
● List items can be traversed or iterated using for and while loops, either
through elements directly or through indices.
Ways to Traverse a List
syntax for loop move through each
element in the list and prints
for item in list_name:
each element one by one.
print(item)
syntax
while loop continues until the
while index < len(list_name): index reaches the length of
the list, printing each
print(list_name[index])
element in the process.
index += 1
Examples of Traversing a List
Code 1 Code 3
1 #traversing through each item 1 #traversing using while loop
2 num = [1, 2, 3, 4, 5] 2 num = [1, 2, 3, 4, 5]
3 for item in num: 3 index = 0
4 print(item, end=",") 4 while index < len(num):
5 5 print(num[index],end=",")
6 6 index += 1
Code 2
1 #traversing through each item using index Output
2 num = [1, 2, 3, 4, 5]
1,2,3,4,5
3 for index in range(len(num)):
4 print(num[index],end=",")
Demo 1 - Calculating Average Temperature
The temperature for last 7 days in Thimphu has been recorded in the list below.
temperatures = [22, 23, 24, 22, 20, 18, 19]
Write a Python program to find the average temperature in Thimphu.
Code
1 temperatures = [22, 23, 24, 22, 20, 18, 19]
2 total_temp=0
3 for temp in temperatures:
4 total_temp = total_temp + temp
Output
5 avg = total_temp/7
6 print(f"Avg temp: {avg}") Avg temp: 38
Demo 2 - Creating a Menu of Bhutanese Dishes
Write a Python program that display a menu of Bhutanese traditional dishes.
Make the menu display the list of Bhutanese dishes as given below.
Output
—------Menu—-------
Dish 1 : Ema Datshi
Dish 2 : Jasha Maroo
Dish 3 : Phaksha Paa
Code
1 print("—------Menu—-------")
2 dishes = ["Ema Datshi", "Jasha Maroo", "Phaksha Paa"]
3 for i in range(len(dishes)):
4 print("Dish",i+1,":",dishes[i])
Activity 1 - Calculating Average Mark
Sonam has scored following marks in different subjects in class IX. Write a Python
program to calculate the average mark scored by Sonam.
marks = [70, 64, 63, 49, 64, 68, 57, 54, 60, 78, 99]
Code
1 marks = [70,64,63,49,64,68,57,54,60,78,99]
2 total_marks=0
3 for x in range(len(marks)):
4 total_marks + = marks[x]
5 print("Sonam’s average mark:",total_marks/11)
Output
Sonam’s average mark: 66.0
Activity 2 - Calculating Sum of Even Numbers
Write a Python program to calculate the sum of all even numbers
in a given list. numbers = [2, 5, 8, 3, 10, 7, 6, 12]
Code
1 numbers = [2, 5, 8, 3, 10, 7, 6, 12]
2 even_sum = 0
3 for num in numbers:
4 if num % 2 == 0:
5 even_sum += num
6 print("Sum of even numbers:", even_sum)
Output
Sum of even numbers: 38
Activity 3 - Checking Vowel or Consonant
Write a Python program using list to check if an alphabet entered by the user is a
vowel or consonant.
Code
1 ch = input("Enter a character to check a vowel or
2 consonant:")
3 if ch in ["a","e","i","o","u"]:
4 print(f'{ch} is a vowel')
5 else:
print(f'{ch} is a consonant')
Output
Enter a character to check a vowel or consonant:a
a is a vowel
Activity 4 - Multiplying First 5 Natural Numbers
Write a Python program using list to multiply the first five natural numbers..
Code
1 number = [1,2,3,4,5]
2 result = 1
3 for x in number:
4 result = result * x
5 print(f'The product of first 5 numbers is {result}')
Output
The product of first 5 numbers is 120
Demo 3 - Displaying Student Code from a List
Write a Python program using while loop to display the student codes from the
given list. Workout the tracing table for the program.
student_code = [20231, 20232, 20233]
Code Output
1 student_code = [20231, 20232, 20233] 20231
2 i = 0 20232
3 while i < len(student_code): 20233
4 print(student_code[i])
5 i += 1
Demo 3 - Displaying Student Code from a List
Tracing Table
i len(student_code) i < condition student_code[i] i +=i
0 3 True 20231 1
1 3 True 20232 2
2 3 True 20233 3
Output
Red
Blue
Green
Activity 6 - Calculating Total Goals Scored by Paro FC
Write a Python program to calculate the total number of goals scored by Paro
FC during the last 5 matches in Bhutan Premier League 2024.
goals = [2, 3, 2, 4, 6]
Solution 1 Solution 2
1 # Using for loop 1 # Using while loop
2 goals = [2, 3, 2, 4, 6] 2 goals = [2, 3, 2, 4, 6]
3 sum = 0 3 index = 0
4 for num in goals: 4 while index < len(goals):
5 sum += num 5 sum += goals[index]
6 print("Total goals:", sum) 6 index += 1
7 print("Total goals:", sum)
Output 8
Total Goals: 17
ACTIVITIES
1. Understanding List Methods
2. Demo 1 - Practicing List Methods
3. Activity 1 - Separating Even and
LIST METHODS
Odd Number
4. Activity 2 - Managing Friend List
5. Activity 3 - Managing a Saving
Account
Understanding Methods in Lists
● Lists in Python come with a variety of methods that enable manipulation,
retrieval, and computation of items.
Insert an element at a
4 insert() specific position
list_name.insert(index,element)
List Methods
SL# Method Description Syntax
Output
Mark List : [78, 50, 63, 40, 70]
Popped element: 63
index value of 5 is 2
sorted list [40, 50, 60, 70, 79]
reversed list [79, 70, 60, 50, 40]
minimum value in list 40
maximum value in list 79
Total marks scored:299
Activity 1 - Separating Even and Odd Number
Write a Python program that iterates through the list
[1,2,3,4,5,6,7,8] and categorize each item into even or odd
numbers. Hint - Use append( ).
Code
1 numbers = [1, 2, 3, 4, 5, 6, 7, 8]
2 even,odd = [],[]
3 for n in numbers:
4
5
if n % 2 == 0: Output
6 even.append(n)
Even numbers: [2, 4, 6, 8]
7 else:
Odd numbers: [1, 3, 5, 7]
8 odd.append(n)
9 print(f'Even numbers: {even}')
10 print(f'Odd numbers: {odd}')
Activity 2 - Managing Friend List
Write a Python program with the list containing name list of your five best
friends. Apply the following conditions using different list methods.
i. Arrange your friends’ name in ascending order.
ii. Add one of your new friends from class IX to the list.
iii. Add another friend from class VIII to the list.
iv. Add another friend “Sonam” to the third position in your list.
v. Remove your friend that is at 4th index in the list.
Activity 2 - Managing Friend List
Code
1 #i.creating a list of friends
2 friends = [“Pema”,”Wangmo”,”Jigme”,”Kinley”,”Sangay”]
3 #ii.arranging the name of friends
4 friends.sort()
5 print(friends)
6 #iii.adding new friend from class IX
7 friends.append( “zangmo”)
8 print(friends)
9 #iv.adding Sonam in your friend list
10 friends.insert(2,“Sonam”)
11 #v.deleting a friend a index 4
12 friends.pop(4)
13 print(friends)
Activity 2 - Managing Friend List
Output
Output
100 is saved for 4 times
In 8th Pema saved Nu.1000
Amount after removing Nu. 560 from list:
[50, 100, 150, 100, 500, 10, 100, 1000, 50, 100, 1500]
Highest amount Pema saved 1500
final amount saved is Nu.3660
Key Points