SlideShare a Scribd company logo
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

What's hot (20)

Python list
Python listPython list
Python list
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python functions
Python functionsPython functions
Python functions
 
Dictionary
DictionaryDictionary
Dictionary
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Python strings
Python stringsPython strings
Python strings
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 

Similar to Python-List.pptx

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
 

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 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
 
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
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 

Recently uploaded

ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
Atif Razi
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
Kamal Acharya
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 

Recently uploaded (20)

shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
retail automation billing system ppt.pptx
retail automation billing system ppt.pptxretail automation billing system ppt.pptx
retail automation billing system ppt.pptx
 
Electrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineElectrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission line
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker project
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdf
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.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)