0% found this document useful (0 votes)
10 views

Data Structure - List.pptx

Uploaded by

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

Data Structure - List.pptx

Uploaded by

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

DATA STRUCTURES - LIST

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.

Lists can dynamically grow or shrink in size,


2. Dynamic Size accommodating varying numbers of elements
without a predefined size limit.

Lists in Python are mutable, allowing for


3. Mutable modifications, additions, or deletions of elements
after the list's creation.

4. Heterogeneous Python lists can store different data types (e.g.,


Elements integers, strings, floats) within the same list.
Demo 1 - Creating a Stationery List
Write a Python program that display a list of stationery used by students.

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

school Motithang HSS Zilukha MSS Babesa MSS

Negative index -3 -2 -1

Positive Indexing Negative Indexing


school[0] Motithang HSS school[-3] Motithang HSS

school[1] Zilukha MSS school[-2] Zilukha MSS

school[2] Babesa HSS school[-1] Babesa HSS


Demo 2 - Displaying Fruits from a List
Write a Python program to create a list of fruits. Then, make the program
display fruit names from the list using positive and negative indexing.
Code
1 fruits = ["apple", "banana", "orange", "grape", "kiwi"]
2 second_fruit = fruits[1] #positive indexing
3 last_fruit = fruits[-1] #negative indexing
4 second_last_fruit = fruits[-2] #negative indexing
5 print("Second fruit (Positive Index):", second_fruit)
6 print("Last fruit (Negative Index):", last_fruit)
7 print("Second last fruit (Negative Index):", second_last_fruit)

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.

● It is used to extract a portion of a list, string, or any sequence type.

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

For the Science presentation in two groups, your teacher has


provided the following name list of students:
students = ["Dorji", "Karma", "Nima", "Sonam", "Wangmo", "Tara"]

Write a Python program using slicing operators to divide the above


students into two groups. Group 1 will consist of students at odd
indices, while group 2 will include students at even indices.
Activity 4 - Grouping Students for Presentation
Code
1 students = ["Dorji", "Karma", "Nima", "Sonam", "Wangmo", "Tara"]
2 group_1 = students[::2] # Students at even indices
3 group_2 = students[1::2] # Students at odd indices
4 # Print the presentation groups
5 print("Group presentation:")
6 print(f"student Group 1:{group_1}")
7 print(f"student Group 2:{group_2}")

Output
Group presentation:
student Group 1:['Tara', 'Sonam', 'Karma']
student Group 2:['Wangmo', 'Nima', 'Dorji']
ACTIVITIES

1. Traversing Elements in a List

2. Demo 1 - Calculating Average Temperature

3. Demo 2 - Creating a Menu of Bhutanese Dishes

4. Activity 1 - Calculate Average Marks

5. Activity 2 - Calculating Sum of Even Numbers


TRAVERSING LIST 6. Activity 3 - Checking Vowel or Consonant

7. Activity 4 - Multiplying First 5 Natural Numbers

8. Demo 3 - Displaying Student Code from a List

9. Activity 5 - Displaying Colours from a List

10. Activity 6 - Calculating Total Goals Scored by


Paro FC
Traversing Items in a List
● Traversing the items of the list is the systematic process of moving
through each item in the list, one after another.

● It involves accessing each item in the list sequentially, either for


processing, manipulation, or analysis of items.

● 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 for loop move through the


indices of the list and prints
for index in range(len(list_name)): each element by accessing
it using the index.
print(list_name[index])

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

3 3 False Terminate loop -


Activity 5 - Displaying Colours from a List
Write a Python program using a while loop to display the colours from the
given lists. colours = ["Red", "Blue", "Green"]
Code
1 colours = ["Red", "Blue", "Green"]
2 index = 0 # Initialize index variable
3 while index < len(colours):
4 print(colours[index])
5 index += 1

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.

● List methods are used to:


○ create copy of the list.
○ manipulate items of the lists.
○ retrieve the items from the lists.
○ sort and reverse the items of the list.
○ perform computation using functions len(), sum().
List Methods
Python has a set of built-in methods that can be used to manipulate items in
the list. Here are some of the common list methods in Python:
SL# Method Description Syntax

The copy method


1 copy() new_list=list_name.copy()
creates new list.

Using Using slicing to create


2 slicing
new_list=original_list[:]
new list

Add an element at the


3 append() list_name.append(element)
end of the list.

Insert an element at a
4 insert() specific position
list_name.insert(index,element)
List Methods
SL# Method Description Syntax

5 Remove the first


remove() list_name.remove(value)
occurrence of a value
Remove and return the
6 pop() element at a specific variable = ist_name.pop(index)
index
Return the index of the
7 index() first occurrence of a index = list_name.index(value)
value
Sort the elements of the
8 sort() list_name.sort()
list in ascending order

count() Return the number of


9 count = list_name.count(element)
occurrences of a value
List Methods
SL# Method Description Syntax

Reverse the order of the


10 reverse() list_name.reverse()
elements in the list

Return the smallest


11 min() min(list_name)
element in the list

Return the largest


12 max() max(List_name)
element in the list

13 Return the sum of all


sum() result = sum(list_name)
elements in the list

Remove all elements


14 clear() list_name.clear()
from the list
Demo 1 - Practicing List Methods
Five students in class VI have scored the marks (78,50,63,40,70) in their science
class test. Write a Python program to perform the following tasks.
1. Create a list containing the marks.
2. Insert the mark 60 at index 2 for the sixth student..
3. Append the mark 79 to the end of the list for the seventh student.
4. Remove the mark 78 from the list.
5. Remove the mark at index 2 and display the removed mark.
6. Find the index of the mark 40 in the list.
7. Sort the marks in an ascending order.
8. Reverse the order of marks in the list.
9. Find the lowest mark from the list.
10. Find the highest mark from the list.
11. Calculate the total marks.
Demo 1 - Practicing List Methods
Code
1 marks = [78,50,63,40,70]# 1. Create a list
2 print("Mark List :",marks)
3 # 2. Inserting the mark 60 at index 2
4 marks.insert(2, 60)
5 # 3. Append the mark 79 to the end of the list
6 marks.append(79)
7 # 4. Remove the mark 78
8 marks.remove(78)
9 # 5. Remove and displaying the mark at index 2
10 element = marks.pop(2)
11 print("Popped element:",element)
12 # 6. Find the index of the mark 40 in the list
Demo 1 - Practicing List Methods
13 index = marks.index(40)
14 print(f'index value of 5 is {index}')
15 # 7. Sort the marks in ascending order
16 marks.sort()
17 print("sorted list",marks)
18 # 8. Reverse the order of marks in the list
19 marks.reverse()
20 print("reversed list",marks)
21 # 9. Finding the lowest mark from the list
22 min_value = min(marks)
23 print("minimum value in list",min_value)
24 # 10. Finding the highest mark from the list
25 max_value = max(marks)
26 print("maximum value in list",max_value)
Demo 1 - Practicing List Methods
27 # 11. Calculate the total marks
28 total = sum(marks)
29 print(f"Total marks scored:{total}")

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

['Jigme', 'Kinley', 'Pema', 'Sangay', 'Wangmo']


['Jigme', 'Kinley', 'Pema', 'Sangay', 'Wangmo', 'zangmo']
['Jigme', 'Kinley', 'Sonam', 'Pema', 'Wangmo', 'zangmo']
Activity 3 - Managing a Saving Account
Pema has started saving money every month beginning from January to buy a guitar.
Given below is the amount he has saved in a year.
saving = [50,100,150,100,500,560,10,100,1000,50,100,1500]
Write a Python program to perform the following conditions to Pema’s saving using
different list methods.

1. Create a list name saving for the money Pema saved.


2. Find out how many times he has saved Nu 100 in a year.
3. Find out in which month he has saved Nu 1000.
4. Remove Nu 560 from the list since he has already spent the money for some
other things.
5. Find the highest amount he has saved.
6. Calculate the total amount of money he has saved in the year.
Activity 3 - Managing a Saving Account
Code
1 # 1. creating a saving list
2 saving = [50,100,150,100,500,560,10,100,1000,50,100,1500]
3 # 2. counting a repeating of amount NU.100 saved
4 x = saving.count(90)
5 print(f'90 is saved for {x} times')
6 # 3. finding the month of Nu.1000
7 y = saving.index(1000)
8 print(f"In {y}th Pema saved Nu.1000")
9 # 4 deleting the number 560 from the saving list
10 saving.remove(560)
11 print("Amount after removing Nu. 560 from list:\n",saving)
Activity 3 - Managing a Saving Account

12 # 5. displaying the highest amount saved


13 print(f'Highest amount Pema saved {max(saving)}')
14 # 6. displaying total amount saved
15 print(f"final amount saved is Nu.{sum(saving)}")

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

● Data structure is a way of organizing and storing data in a computer so


that it can be accessed and modified efficiently.
● A list is a built-in data type that stores an ordered collection of
items/elements.
● Lists are defined using square brackets [ ] and the elements/items are
separated by commas.
● Index refers to a sequential number or value that indicates the
position/location of an element within a list.
● List slicing allows you to create a subsequence (slice) of elements from a
list based on specified indices or range of indices.
Key Points
● List items can be traversed or iterated using for and while loops, either through
elements directly or through indices.
● List methods like append(), insert(), clear(), remove(), pop(), sort(), reverse(),
min(), max(), count(), and sum() are used for manipulation and analysis of items
in the list.
● The benefits of using list is it allows you to store and manage multiple items of
data in a single variable, making it easy to organize, access, and manipulate
information efficiently.
● Lists allow for ordered collection with indexed access (unlike dictionaries and
sets), mutability for dynamic updates (unlike tuples), and can contain duplicate
elements (unlike sets), providing a versatile and efficient way to store and
manipulate data.
བཀྲིན་ཆེ།
THANK YOU

You might also like