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

Lecture 4

Uploaded by

d.q.huy791
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)
19 views

Lecture 4

Uploaded by

d.q.huy791
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/ 35

4/12/2023

List Data Type


for Application Programming with Python

1
4/12/2023

Programming

 Algorithm
- A set of rules or steps used to solve a problem

 Data Structure
- A particular way of organizing data in a computer

What is Not a “Collection”?


Most of our variables have one value in them - when we put a
new value in the variable, the old value is overwritten

$ python
>>> x = 2
>>> x = 4
>>> print(x)
4

2
4/12/2023

A List is a Kind of Collection


 A collection allows us to put many values in a single
“variable”
 A collection is nice because we can carry all many
values around in one convenient package.
friends = [ 'Joseph', 'Glenn', 'Sally' ]

carryon = [ 'socks', 'shirt', 'perfume' ]

List Data Type

3
4/12/2023

CONTENT
 Concept of a collection  Slicing lists
 Lists and definite loops  List methods: append, remove
 Indexing and lookup  Sorting lists
 List mutability  Splitting strings into lists of words
 Functions: len, min, max, sum  Using split to parse strings

LEARNING OUTCOMES

After studying this lecture, you will be able to:

 Understand the concept of mutable sequence types in Python.


 Appreciate the use of list to conveniently store a large amount
of data in memory.
 Create, access & manipulate list objects
 Use various functions & methods to work with list
 Appreciate the use of index for accessing an element from a
sequence.

4
4/12/2023

INTRODUCTION

Like a String, list also is sequence data type. It is an ordered set


of values enclosed in square brackets [ ]. Values in the list can be
modified, i.e. it is mutable. As it is set of values, we can use index
in square brackets [ ] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be
of any type.

INTRODUCTION

 List data type is a container that holds a number of elements


in a given order. For accessing an element of the list, indexing
is used.
 Syntax is :
 Variable name [index]
 It will provide the value at “index+1” in the list. Index here,
has to be an integer (positive or negative)

10

5
4/12/2023

INTRODUCTION

Positive value of index means counting forward from


beginning of the list and negative value means counting
backward from end of the list.
Remember the result of indexing a list is the value of type
accessed from the list.
NOTE: LISTS ARE MUTABLE IN NATURE

11

CREATING LIST:

3rd Element of list


modified.

12

6
4/12/2023

LISTS EXAMPLE
List containing string type data

List containing mixed data

13

LISTS EXAMPLE
A list containing another list known as nested list.

14

7
4/12/2023

LISTS EXAMPLE

Use double subscript to fetch the sub list in a given list.

Similarly, L2[2][0] will fetch you 4 value


L2[2][2] will fetch you 7 value.

15

REPRESENTATION OF LIST OR
STATE DIAGRAM OF LIST

16

8
4/12/2023

STATE DIAGRAM OF LIST


>>> L1 = [45,56,67,20]
State Diagram would be:

Forward Indexing 0 45 -4

1 56 -3

2 67 -2

3 20 -1 Backward Indexing

LIST INDEX
LIST elements
17

STATE DIAGRAM OF LIST


>>> L2 = [“Mouse”,Pendrive”,”RAM”]
State Diagram would be:

Forward Indexing
0 Mouse -3

1 Pendrive -2

2 RAM -1 Backward Indexing

LIST INDEX
LIST elements
18

9
4/12/2023

STATE DIAGRAM OF LIST


>>> L3= []
State Diagram would be:

19

WORKING WITH LIST INDEX

List index works the same way as String index, which is:
An integer value/expression can be used as index.
An Index Error appears, if you try and access element that
does not exist in the list.
An index can have a negative value, in that case counting
happens from the end of the list.

20

10
4/12/2023

LIST - Example

21

LIST - Example

22

11
4/12/2023

CREATING LIST WITH list( ) METHOD

23

CREATING LIST WITH list( ) METHOD

Creating Empty List


With list( ) Method

24

12
4/12/2023

CREATING LIST WITH list( ) METHOD

Creating Empty List


With list( ) Method

25

CREATING MULTIPLE LISTS – LIST MAPPING

26

13
4/12/2023

CREATING MULTIPLE LISTS – LIST MAPPING

Creating a list
and mapping to
other lists.

Creating Multiple List using


assignment statement

27

LIST CONCATENATION

A and B are two different LISTS and third LIST is


created by combining both A and B.

28

14
4/12/2023

LIST SLICING
Like String slicing, Lists can also be sliced, as you have seen
in previous slides.

29

COPYING ALTERNATIVE ELEMENTS OF LIST BY SLICING


Alternative elements of a list can be copied to another list by using ::2
here 2 represents alternative element if you use ::3 this gives you third
element, ::n nth element

30

15
4/12/2023

READING LIST THROUGH KEYBOARD


USE OF append ( ) Method

append () method is used to add elements to the end of list. Every time
new element is assigned using append it will be added at the rear side
of list
Syntax:
Listobject.append(element)
Example
L1.append(587) OR
element=int(input())
L1.append(element)

31

Reading a LIST – Use append ( ) Method

Elements
read during
run time

Contd… next slide

32

16
4/12/2023

Reading a LIST – Use append ( ) Method

OUTPUT

33

Built-in Functions and Lists


>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
 There are a number of 6
functions built into Python >>> print(max(nums))
that take lists as parameters 74
>>> print(min(nums))
 Remember the loops we 3
built? These are much >>> print(sum(nums))
simpler. 154
>>> print(sum(nums)/len(nums))
25.6

34

17
4/12/2023

TRAVERSING LIST

35

TRAVERSING LIST

Fetching all the elements of list using loop

36

18
4/12/2023

TRAVERSING LIST

Traversing list using for loop

37

TRAVERSING LIST

OUT PUT

38

19
4/12/2023

Deleting Elements of LIST

It is possible to delete/remove element(s) from the list.


There are many ways of doing so:
(i) If index is known, we can use pop ( ) or del
(ii) If the element is known, not the index, remove ( ) can be used.
(iii) To remove more than one element, del ( ) with list slice can be
used.
(iv) Using assignment operator

39

Deleting Elements of LIST

1. pop ( ) Method

2. del Method

3. remove ( ) Method

40

20
4/12/2023

Deleting Elements of LIST

1. pop ( ) Method

It removes the element from the specified index, and also


return the element which was removed.
Its syntax is:

List.pop ([index])

41

Deleting Elements of LIST

1. pop ( ) Method

Popped element 67 is assigned to x

42

21
4/12/2023

Deleting Elements of LIST

2. del Method
Syntax :
del Listobject[index]

del removes the


specified element from
the list, but does not
return the deleted value.

del method example

43

Deleting Elements of LIST

3. remove ( ) Method
In case, we know the element to be deleted not the index, of the
element, then remove () can be used.

Syntax is:
listobject.remove(value)

44

22
4/12/2023

SOME MORE METHODS

45

SOME MORE METHODS

1. insert () Method 2. reverse ( ) Method

3. sort ( ) Method 4. clear ( ) Method

5. index ( ) Method 6. extend ( ) Method

46

23
4/12/2023

OTHER METHODS

1. insert () Method
This method allows us to insert
an element, at the given position
specified by its index, and the
remaining elements are shifted to
accommodate the new element.
insert () requires two arguments-
index value and item value.
Its syntax is:
list. insert (index, item)

47

OTHER METHODS

2. reverse ( ) Method
This method can be used to
reverse the elements of the list
in place
Its syntax is:
list.reverse ( )
Method does not return
anything as the reversed list is
stored in the same variable.

48

24
4/12/2023

OTHER METHODS

3. sort ( ) Method
For arranging elements in an
order, Python provides a
method sort ( ) and a function
sorted ( ). sort ( ) modifies the
list in place and sorted()
returns a new sorted list.

Default Ascending
Order sorting

49

OTHER METHODS
For Example:

Descending order

50

25
4/12/2023

OTHER METHODS

3. sort ( ) Method For Example:

Sorting using key value (length of string)

51

OTHER METHODS

4. clear ( ) Method

clear() method deletes


or clears the content of
list. For Example:

52

26
4/12/2023

OTHER METHODS

5. index ( ) Method

To know the index of an


element in a given list

53

OTHER METHODS

6. extend ( ) Method

Extending a given list with


another list.

54

27
4/12/2023

PROGRAMS ON LISTS

55

PROGRAMS ON LISTS

At easy level
1.Write a Python program to sum all the items in a list.

def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))

56

28
4/12/2023

PROGRAMS ON LISTS

At easy level
2. Write a Python program to get the
largest number from a list.

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

57

58

29
4/12/2023

PROGRAMS ON LISTS

3. Write a Python program to


check a list is empty or not.

def check_list():
l = []
if not l:
print("List is empty")
print(check_list())

59

60

30
4/12/2023

PROGRAMS ON LISTS

4. Write a Python program to clone


or copy a list.

def clone_list():
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

61

AT AVERAGE LEVEL

5. Write a Python function that takes two lists and returns True if they have at
least one common member.

def common_data(list1, list2):


result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))

62

31
4/12/2023

AVERAGE PROGRAMS ON LISTS

5. Write a Python function that takes two lists and returns True if they have
at least one common member.

def common_data(list1, list2):


result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))

63

AVERAGE PROGRAMS ON LISTS

6. Write a Python program to generate and print a list of first and last 5
elements where the values are square of numbers between 1 and 30 (both
included).

def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l[:5])
print(l[-5:])

printValues()

64

32
4/12/2023

ABOVE AVERAGE PROGRAMS ON LISTS

7 Write a Python program to generate and print a list except for the first 5
elements, where the values are square of numbers between 1 and 30 (both
included).

def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l[5:])

printValues()

65

ABOVE AVERAGE PROGRAMS ON LISTS

8. Write a Python program to print the numbers of a specified list after


removing even numbers from it.

def num_prn():
num = [7,8, 120, 25, 44, 20, 27]
num = [x for x in num if x%2!=0]
print(num)
num_prn()

66

33
4/12/2023

ABOVE AVERAGE PROGRAMS ON LISTS


9. Write a Python program to print a specified list after removing the 0th,
4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']

def prn_list():
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow’]
color = [x for (i,x) in enumerate(color) if i not in (0,4,5)]
print(color)
prn_list()

67

68

34
4/12/2023

69

35

You might also like