SlideShare a Scribd company logo
1 of 60
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 8
Fundamentals of Programming
Lists
Like a string, a list is a sequence of values
In a string, the values are characters; in a list, they can be any
type
The values in list are called elements or sometimes items
There are several ways to create a new list; the simplest is to
enclose the elements in square brackets (“[" and “]”)
[10, 20, 30, 40]
['python', 'java', 'c']
The first example is a list of four integers
The second is a list of three strings
The elements of a list don’t have to be the same type
The following list contains a string, a float, an integer, and another list:
['zeeshan', 2.0, 5, [10, 20]]
A list within another list is nested
A list that contains no elements is called an empty list; you can create
one with empty brackets, []
>>> student_names = ['Adnan', 'Zeeshan', 'Fatima']
>>> numbers = [17, 123]
>>> empty = []
>>> print(student_names, numbers, empty)
['Adnan', 'Zeeshan', 'Fatima']
[17, 123]
[]
Accessing the elements of a list is the same as for accessing the
characters of a string: the bracket operator
>>> print(student_names[0])
Adnan
Lists are mutable
Unlike strings, lists are mutable because you can change the order of
items in a list or reassign an item in a list
When the bracket operator appears on the left side of an assignment,
it identifies the element of the list that will be assigned
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
List indices work the same way as string indices:
• Any integer expression can be used as an index
• If you try to read or write an element that does not exist, you get
an IndexError
• If an index has a negative value, it counts backward from the
end of the list
IN Operator
The in operator also works on lists
>>> student_names = ['Adnan', 'Zeeshan', 'Fatima']
>>> 'Zeeshan' in student_names
True
>>> 'Javed' in student_names
False
Traversing a list
for student_name in student_names:
print(student_name)
Index Plus Element
for index, student_name in enumerate(student_names):
print(index, student_name)
for index, student_name in enumerate(student_names,
start=10):
print(index, student_name)
Range
range(start, stop[, step])
Return an object that produces a sequence of integers from start
(inclusive) to stop (exclusive) by step
Updating a List
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
A for loop over an empty list never executes the body:
for x in empty:
print('This will not print.')
Although a list can contain another list, the nested list still counts
as a single element.
The length of this list is four:
['zeeshan', 1, ['Javed', 'Bilal', 'Saleem'], [1, 2, 3]]
List Operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[3:]
['d', 'e', 'f']
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before
performing operations that fold, spindle, or mutilate lists.
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']
List methods
Python provides methods that operate on lists. For example,
append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
List methods
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
>>> t1 = ['a', 'b', 'c']
>>> t1.insert(3, 'd')
>>> print(t1)
['a', 'b', 'c', 'd']
sort arranges the elements of the list from low to high
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
>>> nums = [3, 41, 12, 9, 74, 15]
>>> nums.sort()
>>> nums.sort(reverse=True)
sorting without altering original list
>>> nums = [3, 41, 12, 9, 74, 15]
>>> sorted(nums)
Deleting elements
There are several ways to delete elements from a list. If you know the
index of the element you want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
pop modifies the list and returns the element that was removed
If you don’t provide an index, it deletes and returns the last
element
Del
If you don’t need the removed value, you can use the del
operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
['a', 'c']
Remove
If you know the element you want to remove (but not the index),
you can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']
To remove more than one element, you can use del with a slice
index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']
>>> student_names = ['Adnan', 'Zeeshan', 'Fatima']
>>> student_names.reverse()
Lists and functions
There are a number of built-in functions that can be used on lists that allow
you to quickly look through a list without writing your own loops
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
6
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25
>>> nums = [3, 41, 12, 9, 74, 15]
>>> nums.index(15)
total = 0
count = 0
while True:
number = input('Enter a number:')
if number == 'done':
break
value = float(number)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
numlist = list()
while True:
number = input('Enter a number:')
if number == 'done':
break
value = float(number)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
Lists and strings
A string is a sequence of characters and a list is a sequence of
values, but a list of characters is not the same as a string
To convert from a string to a list of characters, you can use list
>>> s = 'zeeshan'
>>> t = list(s)
>>> print(t)
['z', 'e', 'e', 's', 'h', 'a', 'n']
The list function breaks a string into individual letters. If you want
to break a string into words, you can use the split method:
>>> s = 'computer science department'
>>> t = s.split()
>>> print(t)
['computer', 'science', 'department']
>>> print(t[2])
department
You can call split with an optional argument called a delimiter that
specifies which characters to use as word boundaries. The
following example uses a hyphen as a delimiter:
>>> s = 'zeeshan-zeeshan-zeeshan'
>>> delimiter = '-'
>>> s.split(delimiter)
['zeeshan', 'zeeshan', 'zeeshan']
join is the inverse of split
It takes a list of strings and concatenates the elements
join is a string method, so you have to invoke it on the delimiter
and pass the list as a parameter:
>>> t = 'computer science department'
>>> delimiter = ' '
>>> delimiter.join(t)
Object and Values
If we execute these assignment statements:
a = 'banana'
b = 'banana'
we know that a and b both refer to a string but we don’t know
whether they refer to the same string
There are two possible states:
In one case, a and b refer to two different objects that have the
same value
In the second case, they refer to the same object
To check whether two variables refer to the same object, you can
use the is operator
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
Python only created one string object, and both a and b refer to
it. But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case we would say that the two lists are equivalent,
because they have the same elements, but not identical,
because they are not the same object.
If two objects are identical, they are also equivalent, but if they
are equivalent, they are not necessarily identical
Aliasing
If a refers to an object and you assign b = a, then both variables
refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
a
b
[1, 2, 3]
The association of a variable with an object is called a reference
In this example, there are two references to the same object
An object with more than one reference has more than one
name, so we say that the object is aliased
If the aliased object is mutable, changes made with one alias
affect the other:
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
Although this behavior can be useful, it is error-prone
In general, it is safer to avoid aliasing when you are working with mutable
objects
For immutable objects like strings, aliasing is not as much of a problem. In
this example:
a = 'banana'
b = 'banana '
it almost never makes a difference whether a and b refer to the same string
or not
List arguments
When you pass a list to a function, the function gets a reference
to the list
If the function modifies a list parameter, the caller sees the
change
For example, delete_head removes the first element from a list
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print(letters)
['b', 'c']
The parameter t and the variable letters are aliases for the same
object
It is important to distinguish between operations that modify lists and
operations that create new lists. For example, the append method
modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False
This difference is important when you write functions that are
supposed to modify lists
For example, this function does not delete the head of a list:
def bad_delete_head(t):
t = t[1:]
The slice operator creates a new list and the assignment makes t refer
to it, but none of that has any effect on the list that was passed as an
argument
An alternative is to write a function that creates and returns a new list
For example, tail returns all but the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is
used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print(rest)
['b', 'c']

More Related Content

What's hot (19)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
List in Python
List in PythonList in Python
List in Python
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Python list
Python listPython list
Python list
 
Python list
Python listPython list
Python list
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Array
ArrayArray
Array
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
1. python
1. python1. python
1. python
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 

Similar to Python Lecture 8

Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
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.pdfAsst.prof M.Gokilavani
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir1
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdfAUNGHTET61
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184Mahmoud Samir Fayed
 
Python programming lab3 250215
Python programming lab3 250215Python programming lab3 250215
Python programming lab3 250215profbnk
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84Mahmoud Samir Fayed
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88Mahmoud Samir Fayed
 
Python List.ppt
Python List.pptPython List.ppt
Python List.pptT PRIYA
 
Notes3
Notes3Notes3
Notes3hccit
 

Similar to Python Lecture 8 (20)

Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
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
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
Python programming lab3 250215
Python programming lab3 250215Python programming lab3 250215
Python programming lab3 250215
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84
 
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)
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88
 
Python List.ppt
Python List.pptPython List.ppt
Python List.ppt
 
Notes3
Notes3Notes3
Notes3
 

More from Inzamam Baig

More from Inzamam Baig (11)

Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Recently uploaded

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Python Lecture 8

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 8 Fundamentals of Programming
  • 2. Lists Like a string, a list is a sequence of values In a string, the values are characters; in a list, they can be any type The values in list are called elements or sometimes items There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“[" and “]”)
  • 3. [10, 20, 30, 40] ['python', 'java', 'c'] The first example is a list of four integers The second is a list of three strings
  • 4. The elements of a list don’t have to be the same type The following list contains a string, a float, an integer, and another list: ['zeeshan', 2.0, 5, [10, 20]] A list within another list is nested A list that contains no elements is called an empty list; you can create one with empty brackets, []
  • 5. >>> student_names = ['Adnan', 'Zeeshan', 'Fatima'] >>> numbers = [17, 123] >>> empty = [] >>> print(student_names, numbers, empty) ['Adnan', 'Zeeshan', 'Fatima'] [17, 123] []
  • 6. Accessing the elements of a list is the same as for accessing the characters of a string: the bracket operator >>> print(student_names[0]) Adnan
  • 7. Lists are mutable Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned >>> numbers = [17, 123] >>> numbers[1] = 5 >>> print(numbers) [17, 5]
  • 8. List indices work the same way as string indices: • Any integer expression can be used as an index • If you try to read or write an element that does not exist, you get an IndexError • If an index has a negative value, it counts backward from the end of the list
  • 9. IN Operator The in operator also works on lists >>> student_names = ['Adnan', 'Zeeshan', 'Fatima'] >>> 'Zeeshan' in student_names True >>> 'Javed' in student_names False
  • 10. Traversing a list for student_name in student_names: print(student_name)
  • 11. Index Plus Element for index, student_name in enumerate(student_names): print(index, student_name)
  • 12. for index, student_name in enumerate(student_names, start=10): print(index, student_name)
  • 13. Range range(start, stop[, step]) Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step
  • 14. Updating a List for i in range(len(numbers)): numbers[i] = numbers[i] * 2
  • 15. A for loop over an empty list never executes the body: for x in empty: print('This will not print.')
  • 16. Although a list can contain another list, the nested list still counts as a single element. The length of this list is four: ['zeeshan', 1, ['Javed', 'Bilal', 'Saleem'], [1, 2, 3]]
  • 17. List Operations The + operator concatenates lists: >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print(c) [1, 2, 3, 4, 5, 6]
  • 18. Similarly, the * operator repeats a list a given number of times: >>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
  • 19. List slices The slice operator also works on lists: >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd']
  • 20. >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[3:] ['d', 'e', 'f'] >>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
  • 21. Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate lists. >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> print(t) ['a', 'x', 'y', 'd', 'e', 'f']
  • 22. List methods Python provides methods that operate on lists. For example, append adds a new element to the end of a list: >>> t = ['a', 'b', 'c'] >>> t.append('d') >>> print(t) ['a', 'b', 'c', 'd']
  • 23. List methods extend takes a list as an argument and appends all of the elements: >>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> print(t1) ['a', 'b', 'c', 'd', 'e']
  • 24. >>> t1 = ['a', 'b', 'c'] >>> t1.insert(3, 'd') >>> print(t1) ['a', 'b', 'c', 'd']
  • 25. sort arranges the elements of the list from low to high >>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> print(t) ['a', 'b', 'c', 'd', 'e']
  • 26. >>> nums = [3, 41, 12, 9, 74, 15] >>> nums.sort() >>> nums.sort(reverse=True)
  • 27. sorting without altering original list >>> nums = [3, 41, 12, 9, 74, 15] >>> sorted(nums)
  • 28. Deleting elements There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop: >>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> print(t) ['a', 'c'] >>> print(x) b
  • 29. pop modifies the list and returns the element that was removed If you don’t provide an index, it deletes and returns the last element
  • 30. Del If you don’t need the removed value, you can use the del operator: >>> t = ['a', 'b', 'c'] >>> del t[1] >>> print(t) ['a', 'c']
  • 31. Remove If you know the element you want to remove (but not the index), you can use remove: >>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> print(t) ['a', 'c']
  • 32. To remove more than one element, you can use del with a slice index: >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> print(t) ['a', 'f']
  • 33. >>> student_names = ['Adnan', 'Zeeshan', 'Fatima'] >>> student_names.reverse()
  • 34. Lists and functions There are a number of built-in functions that can be used on lists that allow you to quickly look through a list without writing your own loops >>> nums = [3, 41, 12, 9, 74, 15] >>> print(len(nums)) 6 >>> print(max(nums)) 74 >>> print(min(nums)) 3
  • 36. >>> nums = [3, 41, 12, 9, 74, 15] >>> nums.index(15)
  • 37. total = 0 count = 0 while True: number = input('Enter a number:') if number == 'done': break value = float(number) total = total + value count = count + 1 average = total / count print('Average:', average)
  • 38. numlist = list() while True: number = input('Enter a number:') if number == 'done': break value = float(number) numlist.append(value) average = sum(numlist) / len(numlist) print('Average:', average)
  • 39. Lists and strings A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string To convert from a string to a list of characters, you can use list >>> s = 'zeeshan' >>> t = list(s) >>> print(t) ['z', 'e', 'e', 's', 'h', 'a', 'n']
  • 40. The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method: >>> s = 'computer science department' >>> t = s.split() >>> print(t) ['computer', 'science', 'department'] >>> print(t[2]) department
  • 41. You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter: >>> s = 'zeeshan-zeeshan-zeeshan' >>> delimiter = '-' >>> s.split(delimiter) ['zeeshan', 'zeeshan', 'zeeshan']
  • 42. join is the inverse of split It takes a list of strings and concatenates the elements join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter: >>> t = 'computer science department' >>> delimiter = ' ' >>> delimiter.join(t)
  • 43. Object and Values If we execute these assignment statements: a = 'banana' b = 'banana' we know that a and b both refer to a string but we don’t know whether they refer to the same string
  • 44. There are two possible states:
  • 45. In one case, a and b refer to two different objects that have the same value In the second case, they refer to the same object To check whether two variables refer to the same object, you can use the is operator
  • 46. >>> a = 'banana' >>> b = 'banana' >>> a is b True
  • 47. Python only created one string object, and both a and b refer to it. But when you create two lists, you get two objects: >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False
  • 48. In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical
  • 49. Aliasing If a refers to an object and you assign b = a, then both variables refer to the same object: >>> a = [1, 2, 3] >>> b = a >>> b is a True
  • 51. The association of a variable with an object is called a reference In this example, there are two references to the same object An object with more than one reference has more than one name, so we say that the object is aliased
  • 52. If the aliased object is mutable, changes made with one alias affect the other: >>> b[0] = 17 >>> print(a) [17, 2, 3]
  • 53. Although this behavior can be useful, it is error-prone In general, it is safer to avoid aliasing when you are working with mutable objects For immutable objects like strings, aliasing is not as much of a problem. In this example: a = 'banana' b = 'banana ' it almost never makes a difference whether a and b refer to the same string or not
  • 54. List arguments When you pass a list to a function, the function gets a reference to the list If the function modifies a list parameter, the caller sees the change For example, delete_head removes the first element from a list def delete_head(t): del t[0]
  • 55. Here’s how it is used: >>> letters = ['a', 'b', 'c'] >>> delete_head(letters) >>> print(letters) ['b', 'c'] The parameter t and the variable letters are aliases for the same object
  • 56. It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list: >>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print(t1) [1, 2, 3] >>> print(t2) None
  • 57. >>> t3 = t1 + [3] >>> print(t3) [1, 2, 3] >>> t2 is t3 False
  • 58. This difference is important when you write functions that are supposed to modify lists For example, this function does not delete the head of a list: def bad_delete_head(t): t = t[1:]
  • 59. The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument An alternative is to write a function that creates and returns a new list For example, tail returns all but the first element of a list: def tail(t): return t[1:]
  • 60. This function leaves the original list unmodified. Here’s how it is used: >>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> print(rest) ['b', 'c']

Editor's Notes

  1. If there are more than one element append will still treat it as single element
  2. Extends list by appending elements from the iterable.
  3. Most list methods are void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result
  4. The return value from remove is None
  5. As usual, the slice selects all the elements up to, but not including, the second index
  6. The sum() function only works when the list elements are numbers. The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable
  7. Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid the letter “l” because it looks too much like the number “1”. So that’s why I use “t”.
  8. Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list
  9. In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, “”, as a delimiter