SlideShare ist ein Scribd-Unternehmen logo
1 von 81
CHAPTER 15
LISTS
Unit 2:
Computational Thinking and Programming
XI
Computer Science (083)
Board : CBSE
Courtesy CBSE
Unit II
Computational Thinking and Programming
(60 Theory periods + 45 Practical Periods)
DCSc & Engg, PGDCA,ADCA,MCA.MSc(IT),Mtech(IT),MPhil (Comp. Sci)
Department of Computer Science, Sainik School Amaravathinagar
Cell No: 9431453730
Praveen M Jigajinni
Prepared by
Courtesy CBSE
LEARNING OUTCOMES
After studying this lesson, students
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.
LEARNING OUTCOMES
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
We can also say that 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
value which can be positive or negative.
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.
INTRODUCTION
NOTE: LISTS ARE MUTABLE IN NATURE
CREATING LIST
LISTS EXAMPLE
3rd Element of
list modified.
LISTS EXAMPLE
List containing string type data
List containing mixed data
A list containing another list known as
nested list.
LISTS EXAMPLE
Use double subscript to fetch the sub
list in a given list.
LISTS EXAMPLE
Similarly, L2[2][0] will fetch you 4 value
L2[2][2] will fetch you 7 value.
REPRESENTATION OF LIST OR
STATE DIAGRAM OF LIST
STATE DIAGRAM OF LIST
>>> L1 = [45,56,67,20]
State Diagram would be:
Forward Indexing
Backward Indexing
0
1
2
3
-4
-3
-2
-1
45
56
67
20
LIST INDEX
LIST elements
STATE DIAGRAM OF LIST
>>> L2 = [“Mouse”,Pendrive”,”RAM”]
State Diagram would be:
Forward Indexing
Backward Indexing
0
1
2
-3
-2
-1
Mouse
Pendrive
RAM
LIST INDEX
LIST elements
STATE DIAGRAM OF LIST
>>> L3= []
State Diagram would be:
WORKING WITH LIST INDEX
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.
SOME MORE EXAMPLE
LIST - Example
LIST - Example
CREATING LIST WITH list( ) METHOD
CREATING LIST WITH list( ) METHOD
Creating Empty List
With list( ) Method
CREATING LIST WITH list( ) METHOD
Creating Empty List
With list( ) Method
CREATING MULTIPLE LISTS – LIST MAPPING
CREATING MULTIPLE LISTS – LIST MAPPING
Creating Multiple List using assignment statement
Creating a list
and mapping to
other lists.
LIST CONCATENATION
LIST CONCATENATION
A and B are two different LISTS
and third LIST is created by combining
both A and B.
LIST SLICING
Like String slicing, Lists can also be
sliced, as you have seen in previous slides.
LIST SLICING
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
COPYING ALTERNATIVE
ELEMENTS OF LIST BY SLICING
READING LIST THROUGH KEYBOARD
USE OF append ( ) Method
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)
Reading a LIST – Use append ( ) Method
Elements
read during
run time
Contd… next slide
Reading a LIST – Use append ( ) Method
OUTPUT
TRAVERSING LIST
TRAVERSING LIST
Fetching all the elements of list using loop
TRAVERSING LIST
Traversing list using for loop
Contd… next slide
TRAVERSING LIST
OUT PUT
Deleting Elements of LIST
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
Deleting Elements of LIST
1. pop ( ) Method
2. del Method
3. remove ( ) Method
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])
Deleting Elements of LIST
1. pop ( ) Method
For Example:
Popped element 67 is assigned to x
Deleting Elements of LIST
2. del Method
del removes the specified element from
the list, but does not return the deleted value.
Syntax :
del Listobject[index]
del method example
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)
>>>L1.remove(60)
contd…
Deleting Elements of LIST
3. remove ( ) Method
SOME MORE METHODS
SOME MORE METHODS
1. insert () Method 2. reverse ( ) Method
3. sort ( ) Method 4. clear ( ) Method
5. index ( ) Method 6. extend ( ) Method
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)
OTHER METHODS
1. insert () Method For Example:
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.
OTHER METHODS
2. reverse ( ) Method For Example:
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.
OTHER METHODS
3. sort ( ) Method
For Example:
Default Ascending
Order sorting
OTHER METHODS
3. sort ( ) Method
For Example:
Descending order
OTHER METHODS
3. sort ( ) Method
For Example:
Sorting using key value (length of string)
OTHER METHODS
4. clear ( ) Method clear() method deletes
or clears the content of list. For Example:
OTHER METHODS
5. index ( ) Method To know the index of an
element in a given list
For Example:
OTHER METHODS
6. extend ( ) Method Extending a given list with
another list.
For Example:
PROGRAMS ON LISTS
BELLOW AVERAGE PROGRAMS ON LISTS
PROGRAMS ON LISTS
BELLOW AVERAGE PROGRAMS ON LISTS
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]))
PROGRAMS ON LISTS
BELLOW AVERAGE PROGRAMS ON LISTS
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]))
PROGRAMS ON LISTS
BELLOW AVERAGE 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")
PROGRAMS ON LISTS
BELLOW AVERAGE 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)
PROGRAMS ON LISTS
AVERAGE PROGRAMS ON LISTS
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]))
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]))
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()
ABOVE AVERAGE PROGRAMS ON LISTS
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()
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)
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)
CLASS WORK/HOME WORK
CLASS WORK/HOME WORK
1. Write a Python program to generate a 3*4*6
3D array whose each element is *.
2.Write a Python program to shuffle and print a
specified list.
3. Write a Python program to get the difference
between the two lists.
4. Write a Python program access the index of a
list.
5. Write a Python program to convert a list of
characters into a string.
6. Write a Python program to find the index of an
item in a specified list
Class Test
Class Test
Time: 40 Min Max Marks: 20
1. What is list? 02
2. Explain the various ways of creating
list 03
3. Explain 5 list built in methods
10
4. Explain sort method with its various
forms 05
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
11 Unit1 Chapter 1 Getting Started With Python
11   Unit1 Chapter 1 Getting Started With Python11   Unit1 Chapter 1 Getting Started With Python
11 Unit1 Chapter 1 Getting Started With Python
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Python for loop
Python for loopPython for loop
Python for loop
 
Stack
StackStack
Stack
 
Sets in python
Sets in pythonSets in python
Sets in python
 
stack & queue
stack & queuestack & queue
stack & queue
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Binary search
Binary searchBinary search
Binary search
 
Stack
StackStack
Stack
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Linked List
Linked ListLinked List
Linked List
 
single linked list
single linked listsingle linked list
single linked list
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Data types in python
Data types in pythonData types in python
Data types in python
 

Ähnlich wie Chapter 15 Lists

Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 

Ähnlich wie Chapter 15 Lists (20)

Python list
Python listPython list
Python list
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
Python lists
Python listsPython lists
Python lists
 
Python list
Python listPython list
Python list
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdf
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 

Mehr von Praveen M Jigajinni

Mehr von Praveen M Jigajinni (20)

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithms
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Unit 3 MongDB
Unit 3 MongDBUnit 3 MongDB
Unit 3 MongDB
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
Chapter 9 python fundamentals
Chapter 9 python fundamentalsChapter 9 python fundamentals
Chapter 9 python fundamentals
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinking
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow charts
 
Chapter 5 boolean algebra
Chapter 5 boolean algebraChapter 5 boolean algebra
Chapter 5 boolean algebra
 
Chapter 4 number system
Chapter 4 number systemChapter 4 number system
Chapter 4 number system
 
Chapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computingChapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computing
 
Chapter 2 operating systems
Chapter 2 operating systemsChapter 2 operating systems
Chapter 2 operating systems
 
Chapter 1 computer fundamentals
Chapter 1 computer  fundamentalsChapter 1 computer  fundamentals
Chapter 1 computer fundamentals
 
Chapter 0 syllabus 2019 20
Chapter 0  syllabus 2019 20Chapter 0  syllabus 2019 20
Chapter 0 syllabus 2019 20
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Kürzlich hochgeladen (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

Chapter 15 Lists

  • 2. Unit 2: Computational Thinking and Programming XI Computer Science (083) Board : CBSE Courtesy CBSE
  • 3. Unit II Computational Thinking and Programming (60 Theory periods + 45 Practical Periods) DCSc & Engg, PGDCA,ADCA,MCA.MSc(IT),Mtech(IT),MPhil (Comp. Sci) Department of Computer Science, Sainik School Amaravathinagar Cell No: 9431453730 Praveen M Jigajinni Prepared by Courtesy CBSE
  • 5. After studying this lesson, students 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. LEARNING OUTCOMES
  • 7. 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
  • 8. We can also say that 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 value which can be positive or negative. INTRODUCTION
  • 9. 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. INTRODUCTION NOTE: LISTS ARE MUTABLE IN NATURE
  • 11. LISTS EXAMPLE 3rd Element of list modified.
  • 12. LISTS EXAMPLE List containing string type data List containing mixed data
  • 13. A list containing another list known as nested list. LISTS EXAMPLE
  • 14. Use double subscript to fetch the sub list in a given list. LISTS EXAMPLE 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. STATE DIAGRAM OF LIST >>> L1 = [45,56,67,20] State Diagram would be: Forward Indexing Backward Indexing 0 1 2 3 -4 -3 -2 -1 45 56 67 20 LIST INDEX LIST elements
  • 17. STATE DIAGRAM OF LIST >>> L2 = [“Mouse”,Pendrive”,”RAM”] State Diagram would be: Forward Indexing Backward Indexing 0 1 2 -3 -2 -1 Mouse Pendrive RAM LIST INDEX LIST elements
  • 18. STATE DIAGRAM OF LIST >>> L3= [] State Diagram would be:
  • 20. 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.
  • 24. CREATING LIST WITH list( ) METHOD
  • 25. CREATING LIST WITH list( ) METHOD Creating Empty List With list( ) Method
  • 26. CREATING LIST WITH list( ) METHOD Creating Empty List With list( ) Method
  • 27. CREATING MULTIPLE LISTS – LIST MAPPING
  • 28. CREATING MULTIPLE LISTS – LIST MAPPING Creating Multiple List using assignment statement Creating a list and mapping to other lists.
  • 30. LIST CONCATENATION A and B are two different LISTS and third LIST is created by combining both A and B.
  • 32. Like String slicing, Lists can also be sliced, as you have seen in previous slides. LIST SLICING
  • 34. 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 COPYING ALTERNATIVE ELEMENTS OF LIST BY SLICING
  • 35. READING LIST THROUGH KEYBOARD USE OF append ( ) Method
  • 36. 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)
  • 37. Reading a LIST – Use append ( ) Method Elements read during run time Contd… next slide
  • 38. Reading a LIST – Use append ( ) Method OUTPUT
  • 40. TRAVERSING LIST Fetching all the elements of list using loop
  • 41. TRAVERSING LIST Traversing list using for loop Contd… next slide
  • 44. 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
  • 45. Deleting Elements of LIST 1. pop ( ) Method 2. del Method 3. remove ( ) Method
  • 46. 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])
  • 47. Deleting Elements of LIST 1. pop ( ) Method For Example: Popped element 67 is assigned to x
  • 48. Deleting Elements of LIST 2. del Method del removes the specified element from the list, but does not return the deleted value. Syntax : del Listobject[index] del method example
  • 49. 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) >>>L1.remove(60) contd…
  • 50. Deleting Elements of LIST 3. remove ( ) Method
  • 52. SOME MORE METHODS 1. insert () Method 2. reverse ( ) Method 3. sort ( ) Method 4. clear ( ) Method 5. index ( ) Method 6. extend ( ) Method
  • 53. 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)
  • 54. OTHER METHODS 1. insert () Method For Example:
  • 55. 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.
  • 56. OTHER METHODS 2. reverse ( ) Method For Example:
  • 57. 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.
  • 58. OTHER METHODS 3. sort ( ) Method For Example: Default Ascending Order sorting
  • 59. OTHER METHODS 3. sort ( ) Method For Example: Descending order
  • 60. OTHER METHODS 3. sort ( ) Method For Example: Sorting using key value (length of string)
  • 61. OTHER METHODS 4. clear ( ) Method clear() method deletes or clears the content of list. For Example:
  • 62. OTHER METHODS 5. index ( ) Method To know the index of an element in a given list For Example:
  • 63. OTHER METHODS 6. extend ( ) Method Extending a given list with another list. For Example:
  • 64. PROGRAMS ON LISTS BELLOW AVERAGE PROGRAMS ON LISTS
  • 65. PROGRAMS ON LISTS BELLOW AVERAGE PROGRAMS ON LISTS 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]))
  • 66. PROGRAMS ON LISTS BELLOW AVERAGE PROGRAMS ON LISTS 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]))
  • 67. PROGRAMS ON LISTS BELLOW AVERAGE 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")
  • 68. PROGRAMS ON LISTS BELLOW AVERAGE 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)
  • 69. PROGRAMS ON LISTS AVERAGE PROGRAMS ON LISTS
  • 70. 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]))
  • 71. 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]))
  • 72. 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()
  • 74. 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()
  • 75. 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)
  • 76. 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)
  • 78. CLASS WORK/HOME WORK 1. Write a Python program to generate a 3*4*6 3D array whose each element is *. 2.Write a Python program to shuffle and print a specified list. 3. Write a Python program to get the difference between the two lists. 4. Write a Python program access the index of a list. 5. Write a Python program to convert a list of characters into a string. 6. Write a Python program to find the index of an item in a specified list
  • 80. Class Test Time: 40 Min Max Marks: 20 1. What is list? 02 2. Explain the various ways of creating list 03 3. Explain 5 list built in methods 10 4. Explain sort method with its various forms 05