SlideShare a Scribd company logo
1 of 32
Python: Lists
List
• A list can store a collection of data of any size.
• Python lists are one of the most versatile data types that allow us to work with multiple elements at once
thislist = ["apple", "banana", "cherry"]
print(thislist)
# a list of programming languages
['Python', 'C++', 'JavaScript’]
# list of integers
my_list = [1, 2, 3]
# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
List Is a
Sequence Type
• Strings and lists are
sequence types in Python
• The sequence operations
for lists are the same as
for strings
Python Math
• Built-in Math Functions
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
x = abs(-7.25)
print(x)
x = pow(4, 3)
print(x)
The Math Module
• Python has also a built-in module called math, which extends the list
of mathematical functions
import math
import math
x = math.sqrt(64)
print(x)
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
import math
x = math.pi
print(x)
https://www.w3schools.com/python/module_math.asp
Functions for Lists
• list1 = [2, 3, 4, 1, 32]
len(list1)
max(list1)
min(list1)
sum(list1)
• import random
random.shuffle(list1)
Access List
Elements
• Index Operator []
• An element in a list can be accessed through the index operator,
using the following syntax:
myList[index]
myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
Out of Range
• Accessing a list out of bounds is a common programming error that
results in a runtime IndexError
• To avoid this error, make sure that you do not use an index beyond
len(myList) – 1
Examples
• my_list = ['p', 'r', 'o', 'b', 'e']
• # first item
• print(my_list[0]) # p
• # third item
• print(my_list[2]) # o
• # fifth item
• print(my_list[4]) # e
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
# Error! Only integer can be used for indexing
print(my_list[4.0])
Negative indexing
• Python also allows the use of negative
numbers as indexes to reference positions
relative to the end of the list
list1 = [2, 3, 5, 2, 33, 21]
list1[-1]
list1[-3]
List Slicing [start : end]
• The index operator allows you to select an element at the specified
index. The slicing operator returns a slice of the list using the syntax
list[start : end].
• The slice is a sublist from index start to index end – 1
list1 = [2, 3, 5, 7, 9, 1]
list1[2 : 4]
list1[ : 4]
list1[2 : ]
list1[ : ]
Negative index in slicing
list1 = [2, 3, 5, 2, 33, 21]
list1[1 : -3]
list1[-4 : -2]
The +, *, and in/not in Operators
• Concatenation operator (+) to join two lists and
• the repetition operator (*) to replicate elements in a list
list1 = [2, 3]
list2 = [1, 9]
list3 = list1 + list2
list4 = 3 * list1
The in/not in Operators
list1 = [2, 3, 5, 2, 33, 21]
2 in list1
Lexicographic order
• Lexicographical order is nothing but the dictionary order or preferably
the order in which words appear in the dictionary. For example,
• let's take three strings, "short", "shorthand" and "small". In the dictionary,
"short" comes before "shorthand" and "shorthand" comes before "small".
This is lexicographical order.
Comparing Lists
• compare lists using the comparison operators (>, >=, <, <=, ==, and !=)
• The comparison uses lexicographical ordering:
• the first two elements are compared, and if they differ this determines the outcome of the comparison;
if they are equal, the next two elements are compared, and so on, until either list is exhausted.
list1 = ["green", "red", "blue"]
list2 = ["red", "blue", "green"]
list2 == list1
list2 != list1
list2 >= list1
list2 > list1
list2 < list1
list2 <= list1
List Comprehension: Elegant way to create
Lists
pow2 = [2 ** x for x in range(10)]
print(pow2)
pow2 = []
for x in range(10):
pow2.append(2 ** x)
Iterating Through a List
for fruit in ['apple','banana','mango']:
print("I like",fruit)
List Methods
Examples
list1 = [2, 3, 4, 1, 32, 4]
list1.append(19)
list1.count(4) # Return the count for number 4
list2 = [99, 54]
list1.extend(list2)
list1.index(4) # Return the index of number 4
list1.insert(1, 25) # Insert 25 at position index 1
More Examples
list1 = [2, 25, 3, 4, 1, 32, 4, 19, 99, 54]
list1.pop(2)
list1.pop() #returns and removes the last element from
list1
ist1.remove(32) # Remove number 32
list1.reverse() # Reverse the list
list1.sort() # Sort the list
List Comprehensions
• list1 = [x for x in range(5)]
• list2 = [0.5 * x for x in list1]
• list3 = [x for x in list2 if x < 1.5]
Deep and shallow copy
list1 = [1, 43]
list2 = list1
list1[0] = 22
print (list1)
print (list2)
print("------------------------------------------------")
list1 = [1, 43]
list2 = [x for x in list1]
list1[0] = 22
print (list1)
print (list2)
import copy
b = copy.deepcopy(a)
Nested List
• A nested list is a list of lists, or any list that has another list as an element (a sublist)
• # creating list
nestedList = [1, 2, ['a', 1], 3]
# indexing list: the sublist has now been accessed
subList = nestedList[2]
# access the first element inside the inner list:
element = nestedList[2][0]
print("List inside the nested list: ", subList)
print("First element of the sublist: ", element)
Creating a
matrix
• This is done by creating a nested list
that only has other lists of equal
length as elements
• The number of elements in
the nested lists is equal to the
number of rows of the matrix.
• The length of the lists inside
the nested list is equal to the
number of columns
A matrix of size 4x3
# create matrix of size 4 x 3
matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]]
rows = len(matrix) # no of rows is no of sublists i.e. len of list
cols = len(matrix[0]) # no of cols is len of sublist
# printing matrix
print("matrix: ")
for i in range(0, rows):
print(matrix[i])
# accessing the element on row 2 and column 1 i.e. 3
print("element on row 2 and column 1: ", matrix[1][0])
# accessing the element on row 3 and column 2 i.e. 7
print("element on row 3 and column 2: ", matrix[2][1])
Distances list
• Each element in the distances list is
another list, so distances is
considered a nested list
distances = [[0, 983, 787, 714, 1375,
967, 1087], [983, 0, 214, 1102, 1505,
1723, 1842], [787, 214, 0, 888, 1549,
1548, 1627], [714, 1102, 888, 0, 661,
781, 810], [1375, 1505, 1549, 661, 0,
1426, 1187], [967, 1723, 1548, 781,
1426, 0, 239], [1087, 1842, 1627, 810,
1187, 239, 0] ]
Questions
• How do you create an empty list and a list with the three integers 1, 32,
and 2?
• Given lst = [30, 1, 12, 14, 10, 0],
• how many elements are in lst?
• What is the index of the first element in lst? What is the index of the last element in
lst?
• What is lst[2]? What is lst[-2]?
• Indicate true or false for the following statements:
(a) Every element in a list must have the same type.
(b) A list’s size is fixed after it is created.
(c) A list can have duplicate elements.
(d) The elements in a list can be accessed via an index operator.
Questions
• Given lst = [30, 1, 2, 1, 0], what is the list after applying each of the
following statements? Assume that each line of code is independent.
• lst.append(40)
• lst.insert(1, 43)
• lst.extend([1, 43])
• lst.remove(1)
• lst.pop(1)
• lst.pop()
• lst.sort()
• lst.reverse()
• random.shuffle(lst)
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
#Another way
print([i**2 for i in range(10)])
Questions
• What are list1 and list2 after the following lines of code?
list1 = [1, 43]
list2 = list1
list1[0] = 22
• What are list1 and list2 after the following lines of code?
list1 = [1, 43]
list2 = [x for x in list1]
list1[0] = 22
• How do you obtain a list from a string? Suppose s1 is welcome. What is
s1.split('o')?
Questions
• What is the output of the following code?
lst = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
lst[i] = lst[i - 1]
print(lst)

More Related Content

What's hot (20)

8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Doubly linked list (animated)
Doubly linked list (animated)Doubly linked list (animated)
Doubly linked list (animated)
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Singly link list
Singly link listSingly link list
Singly link list
 
Linked list
Linked listLinked list
Linked list
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
 
List in Python
List in PythonList in Python
List in Python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Python for loop
Python for loopPython for loop
Python for loop
 
single linked list
single linked listsingle linked list
single linked list
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 

Similar to Python-List.pptx

Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_pythondeepalishinkar1
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of DataIHTMINSTITUTE
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
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.pdfMCCMOTOR
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxGaneshRaghu4
 
Brixon Library Technology Initiative
Brixon Library Technology InitiativeBrixon Library Technology Initiative
Brixon Library Technology InitiativeBasil Bibi
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Data Structure Searching.pptx
Data Structure Searching.pptxData Structure Searching.pptx
Data Structure Searching.pptxSourabhTaneja4
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
lists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Pythonlists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Pythonkvpv2023
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptxssuser8f0410
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 

Similar to Python-List.pptx (20)

updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of Data
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
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
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Brixon Library Technology Initiative
Brixon Library Technology InitiativeBrixon Library Technology Initiative
Brixon Library Technology Initiative
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Data Structure Searching.pptx
Data Structure Searching.pptxData Structure Searching.pptx
Data Structure Searching.pptx
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
lists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Pythonlists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Python
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Python lists
Python listsPython lists
Python lists
 

Recently uploaded

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 

Recently uploaded (20)

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

Python-List.pptx

  • 2. List • A list can store a collection of data of any size. • Python lists are one of the most versatile data types that allow us to work with multiple elements at once thislist = ["apple", "banana", "cherry"] print(thislist) # a list of programming languages ['Python', 'C++', 'JavaScript’] # list of integers my_list = [1, 2, 3] # empty list my_list = [] # list with mixed data types my_list = [1, "Hello", 3.4] # nested list my_list = ["mouse", [8, 4, 6], ['a']]
  • 3. List Is a Sequence Type • Strings and lists are sequence types in Python • The sequence operations for lists are the same as for strings
  • 4. Python Math • Built-in Math Functions x = min(5, 10, 25) y = max(5, 10, 25) print(x) print(y) x = abs(-7.25) print(x) x = pow(4, 3) print(x)
  • 5. The Math Module • Python has also a built-in module called math, which extends the list of mathematical functions import math import math x = math.sqrt(64) print(x) import math x = math.ceil(1.4) y = math.floor(1.4) print(x) # returns 2 print(y) # returns 1 import math x = math.pi print(x) https://www.w3schools.com/python/module_math.asp
  • 6. Functions for Lists • list1 = [2, 3, 4, 1, 32] len(list1) max(list1) min(list1) sum(list1) • import random random.shuffle(list1)
  • 7. Access List Elements • Index Operator [] • An element in a list can be accessed through the index operator, using the following syntax: myList[index] myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
  • 8. Out of Range • Accessing a list out of bounds is a common programming error that results in a runtime IndexError • To avoid this error, make sure that you do not use an index beyond len(myList) – 1
  • 9. Examples • my_list = ['p', 'r', 'o', 'b', 'e'] • # first item • print(my_list[0]) # p • # third item • print(my_list[2]) # o • # fifth item • print(my_list[4]) # e # Nested List n_list = ["Happy", [2, 0, 1, 5]] # Nested indexing print(n_list[0][1]) print(n_list[1][3]) # Error! Only integer can be used for indexing print(my_list[4.0])
  • 10. Negative indexing • Python also allows the use of negative numbers as indexes to reference positions relative to the end of the list list1 = [2, 3, 5, 2, 33, 21] list1[-1] list1[-3]
  • 11. List Slicing [start : end] • The index operator allows you to select an element at the specified index. The slicing operator returns a slice of the list using the syntax list[start : end]. • The slice is a sublist from index start to index end – 1 list1 = [2, 3, 5, 7, 9, 1] list1[2 : 4] list1[ : 4] list1[2 : ] list1[ : ]
  • 12. Negative index in slicing list1 = [2, 3, 5, 2, 33, 21] list1[1 : -3] list1[-4 : -2]
  • 13. The +, *, and in/not in Operators • Concatenation operator (+) to join two lists and • the repetition operator (*) to replicate elements in a list list1 = [2, 3] list2 = [1, 9] list3 = list1 + list2 list4 = 3 * list1
  • 14. The in/not in Operators list1 = [2, 3, 5, 2, 33, 21] 2 in list1
  • 15. Lexicographic order • Lexicographical order is nothing but the dictionary order or preferably the order in which words appear in the dictionary. For example, • let's take three strings, "short", "shorthand" and "small". In the dictionary, "short" comes before "shorthand" and "shorthand" comes before "small". This is lexicographical order.
  • 16. Comparing Lists • compare lists using the comparison operators (>, >=, <, <=, ==, and !=) • The comparison uses lexicographical ordering: • the first two elements are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two elements are compared, and so on, until either list is exhausted. list1 = ["green", "red", "blue"] list2 = ["red", "blue", "green"] list2 == list1 list2 != list1 list2 >= list1 list2 > list1 list2 < list1 list2 <= list1
  • 17. List Comprehension: Elegant way to create Lists pow2 = [2 ** x for x in range(10)] print(pow2) pow2 = [] for x in range(10): pow2.append(2 ** x)
  • 18. Iterating Through a List for fruit in ['apple','banana','mango']: print("I like",fruit)
  • 20. Examples list1 = [2, 3, 4, 1, 32, 4] list1.append(19) list1.count(4) # Return the count for number 4 list2 = [99, 54] list1.extend(list2) list1.index(4) # Return the index of number 4 list1.insert(1, 25) # Insert 25 at position index 1
  • 21. More Examples list1 = [2, 25, 3, 4, 1, 32, 4, 19, 99, 54] list1.pop(2) list1.pop() #returns and removes the last element from list1 ist1.remove(32) # Remove number 32 list1.reverse() # Reverse the list list1.sort() # Sort the list
  • 22. List Comprehensions • list1 = [x for x in range(5)] • list2 = [0.5 * x for x in list1] • list3 = [x for x in list2 if x < 1.5]
  • 23. Deep and shallow copy list1 = [1, 43] list2 = list1 list1[0] = 22 print (list1) print (list2) print("------------------------------------------------") list1 = [1, 43] list2 = [x for x in list1] list1[0] = 22 print (list1) print (list2) import copy b = copy.deepcopy(a)
  • 24. Nested List • A nested list is a list of lists, or any list that has another list as an element (a sublist) • # creating list nestedList = [1, 2, ['a', 1], 3] # indexing list: the sublist has now been accessed subList = nestedList[2] # access the first element inside the inner list: element = nestedList[2][0] print("List inside the nested list: ", subList) print("First element of the sublist: ", element)
  • 25. Creating a matrix • This is done by creating a nested list that only has other lists of equal length as elements • The number of elements in the nested lists is equal to the number of rows of the matrix. • The length of the lists inside the nested list is equal to the number of columns
  • 26. A matrix of size 4x3 # create matrix of size 4 x 3 matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] rows = len(matrix) # no of rows is no of sublists i.e. len of list cols = len(matrix[0]) # no of cols is len of sublist # printing matrix print("matrix: ") for i in range(0, rows): print(matrix[i]) # accessing the element on row 2 and column 1 i.e. 3 print("element on row 2 and column 1: ", matrix[1][0]) # accessing the element on row 3 and column 2 i.e. 7 print("element on row 3 and column 2: ", matrix[2][1])
  • 27. Distances list • Each element in the distances list is another list, so distances is considered a nested list distances = [[0, 983, 787, 714, 1375, 967, 1087], [983, 0, 214, 1102, 1505, 1723, 1842], [787, 214, 0, 888, 1549, 1548, 1627], [714, 1102, 888, 0, 661, 781, 810], [1375, 1505, 1549, 661, 0, 1426, 1187], [967, 1723, 1548, 781, 1426, 0, 239], [1087, 1842, 1627, 810, 1187, 239, 0] ]
  • 28. Questions • How do you create an empty list and a list with the three integers 1, 32, and 2? • Given lst = [30, 1, 12, 14, 10, 0], • how many elements are in lst? • What is the index of the first element in lst? What is the index of the last element in lst? • What is lst[2]? What is lst[-2]? • Indicate true or false for the following statements: (a) Every element in a list must have the same type. (b) A list’s size is fixed after it is created. (c) A list can have duplicate elements. (d) The elements in a list can be accessed via an index operator.
  • 29. Questions • Given lst = [30, 1, 2, 1, 0], what is the list after applying each of the following statements? Assume that each line of code is independent. • lst.append(40) • lst.insert(1, 43) • lst.extend([1, 43]) • lst.remove(1) • lst.pop(1) • lst.pop() • lst.sort() • lst.reverse() • random.shuffle(lst)
  • 30. squares = [] for i in range(10): squares.append(i**2) print(squares) #Another way print([i**2 for i in range(10)])
  • 31. Questions • What are list1 and list2 after the following lines of code? list1 = [1, 43] list2 = list1 list1[0] = 22 • What are list1 and list2 after the following lines of code? list1 = [1, 43] list2 = [x for x in list1] list1[0] = 22 • How do you obtain a list from a string? Suppose s1 is welcome. What is s1.split('o')?
  • 32. Questions • What is the output of the following code? lst = [1, 2, 3, 4, 5, 6] for i in range(1, 6): lst[i] = lst[i - 1] print(lst)