SlideShare a Scribd company logo
1 of 48
Download to read offline
List, Tuple & Set
Session-V
1
Intro to Robots
What is a List?
■ An ordered set of values:
■ Ordered: 1st
, 2nd
, 3rd
, …
■ Values: can be anything, integers, strings, other lists
■ List values are called elements.
■ A string is an ordered set of characters so it is “like” a
list but not exactly the same thing.
Intro to Robots
The Empty List
x = [ ]
■ The empty list is usually used to initialize a list variable
but not give it any useful elements.
Intro to Robots
Accessing Elements:
■ List elements are accessed via integer indexes starting
at 0 and working up.
numbers = [ 3, 87, 43]
print(numbers[1], numbers[2], numbers[0])
87 43 3
x = 3
print(numbers[x-2])
87
print (numbers[1.0])
TypeError: sequence index must be integer
print (numbers[3])
TypeError: list index out of range
print (numbers[-1]) # a negative index counts
back
3 # from the end of the list
# index -1 is the last element
print (numbers[-3])
Intro to Robots
Accessing Many Elements: ■ By
index value, one at a time (called list traversal)
# list of a known size
horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’]
i = 0
while i < 4:
print (horsemen[i])
i = i + 1
# or if you don’t know how long the list is
i = 0
length = len(horsemen)
while i < length:
print( horsemen[i]) i = i
+ 1
war
famine
pestilence
death
always safer to use len as
an upper bound
always I < length;
never I <= length
Intro to Robots
List Membership:
■ You simply ask if a value is “in” or “not in” a list. ■ This is
always a True/False question.
horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’]
if ‘debauchery’ in horseman:
print( ‘There are more than 4 horsemen of the apocolipse.)
print( ‘debauchery’ not in horsemen)
1
Intro to Robots
List Operations: ■ Add two
lists:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print (c)
[1, 2, 3, 4 ,5, 6]
■ Repeat a list many times:
a = [1, 2, 3]
print (a*3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
■ Exercise: Create a list of 20 zeros.
zeros = [0]*20
Intro to Robots
List Slices:
■ Sometimes you just want a sub-list (slice) of a list.
list[a:b] means
list[a], list[a+1], …, list[b-1]
# all list elements with indexes from a to b;
# including a and excluding b
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
print (vowels[2:4])
[‘i’, ‘o’]
# how do you print out the last element?
print (vowels[2:])
[‘i’, ‘o’, ‘u’]
■ Exercise: What does vowels[:3] mean?
[‘a’, ‘e’, ‘i’]
Intro to Robots
Lists are Mutable
fruit = [‘apple’, ‘orange’, ‘pear’]
fruit[1] = ‘fig’
print fruit
[‘apple’, ‘fig’, ‘pear’]
Intro to Robots
List Slices Used to Modify a List:
■ Suppose you are keeping an ordered list:
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’]
■ And you want to add kate. Assignment doesn’t work!
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’]
names[2] = ‘kate’
print (names)
[‘adam’, ‘carol’, ‘kate’, ‘margot’, ‘phil’]
■ You can add an element by squeezing it into an empty
slice between two list elements:
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’]
names[2:2] = ‘kate’
print (names)
[‘adam’, ‘carol’, ‘henry’, ‘kate’, ‘margot’, ‘phil’]
Starting at index 2
but not including 2;
ie, empty
Intro to Robots
List Deletion:
■ Using the del operator
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’]
del names[3]
print (names)
[‘adam’, ‘carol’, ‘henry’, ‘phil’]
■ Replacing an element with an empty list
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’]
names[3:4] = [ ]
■ Deleting slices
print (names)
[‘adam’, ‘carol’, ‘henry’, ‘phil’]
names = [‘adam’, ‘carol’, ‘henry’, ‘margot’,
‘phil’] del names[1:4]
print (names)
[‘adam’, ‘phil’]
Intro to Robots
Lists, Objects and Values
■ Lists are different:
a = [1, 2, 3]
b = [1, 2, 3]
print( id(a), id(b))
135023431 135024732
■ So this time the memory state picture is:
a b
[1, 2, 3]
[1, 2, 3]
Intro to Robots
Aliasing
■ However, if we assign one variable to another:
a = [1, 2, 3]
b = a
print( id(a), id(b))
135023431 135023431
■ So this time the memory state picture is:
a
[1, 2, 3]
b
■ More importantly, changing b also changes a
b[0] = 0
print a
[0, 2, 3]
Intro to Robots
Cloning a List:
■ Cloning means making an exact but separate copy: ■
Not Cloning:
a = [1, 2, 3]
b = a
print (id(a), id(b))
135023431 135023431
■ Cloning:
a = [1, 2, 3]
b = a[:] # slices are always separate lists
print (id(a), id(b))
135023431 13502652
List Methods:
15
Adding Elements
■ """List are mutable objects represented
■ by []list is an ordered collection"""
■ l=[]
■ print(l)
■ """append adds an item at the end of
■ list"""
■ l.append(9)
■ l.append("hello")
■ l.append(75.2)
■ print(l)
■ """insert adds item at a given
■ index-insert(index,object)"""
■ l.insert(0,90)
■ print(l)
16
Adding Elements
■ l1=[78,23]
■ """extend list by appending
■ elements from object"""
■ l.extend(l1)
■ print(l)
■ l.extend("abc")
■ print(l)
■ l.extend([32,"abc",35.5])
■ print(l)
■ """append can be used to create
■ nested list"""
■ l1=[34,56]
■ l1.append([23,34])
■ print(l1)
17
More Operations..
■ l=[92,56,12,78,1]
■ print(l.count(92))
■ #sort() the list in increasing order of elements"""
■ l.sort()#doesn’t return object –inplace sorting ■
print(l)
■ #sort(reverse=True sort the list in non increasing order"""
■ l.sort(reverse=True)
■ print(l)
■ l.reverse()
■ print(l)
18
Remove/del
■ l=[23,"bill",67, 89, 90,"abc", "xyz"]
■ """remove searches for an element in list and
■ deletes it"""
■ l.remove("abc")
■ print(l)
■ del(l[2])
■ print(l)
■ del(l[2:])
■ print(l)
■ l.extend([34,4,67,90])
■ print(l)
■ #del l[2:4]
■ del(l[:-1])
■ print(l)
■ del l[:]#removes all elements but not list
■ print(l)
■ """delete list"""
■ del l
■ print(l)#NameError: name 'l' not defined
19
Index/pop
■ l=["abc",30,50]
■ x=l.index(30)
■ print(x)
■ """pop function by default removes last element
■ --pop(index)"""
■ numbers.pop()
■ print(numbers)
■ x=numbers.pop(0)
■ print(numbers)
■ x=len(numbers)
■ print(x)
■ x=max(numbers)
■ print(x)
■ x=min(numbers)
■ print(x)
20
Sorted
■ l=[5,4,3,2,1]
■ p=sorted(l)
■ print(p)
21
Array
■ l=array('i')
■ l.append(90)
■ l.append(40)
■ print(l)
■ #l.append(53.25)
■ print(l)
■ l[0]=100
■ print(l)
22
More…
■ s=array('u',"hello")
■ print(s)
■ for ch in s:
■ print(ch)
■ s.reverse()
■ print(s)
■ s.pop()
■ print(s)
■ s.index("l")
■ x=sorted(s)
■ print(x)
■ p=array('i')
■ for x in range(1,6):
■ p.append(x)
■ print(p)
23
typecodes
24
Tuples
■ Same as lists but
■ Immutable
■ Enclosed in parentheses
■ A tuple with a single element must have a comma inside the
parentheses:
■ a = (11,)
Examples
■ >>> mytuple = (11, 22, 33)
■ >>> mytuple[0]
11
■ >>> mytuple[-1]
33
■ >>> mytuple[0:1]
(11,)
■ The comma is required!
Why?
■ No confusion possible between [11] and 11
■ (11) is a perfectly acceptable expression
■ (11) without the comma is the integer 11
■ (11, ) with the comma is a tuple containing the integer 11
Tuples are immutable
■ >>> mytuple = (11, 22, 33)
■ >>> saved = mytuple
■ >>> mytuple += (44,)
■ >>> mytuple
(11, 22, 33, 44)
■ >>> saved
(11, 22, 33)
Things that do not work
■ mytuple += 55
Traceback (most recent call last):Z
…
TypeError:
can only concatenate tuple (not "int") to tuple ■ Can
understand that!
Sorting tuples
■ >>> atuple = (33, 22, 11)
■ >>> atuple.sort()
Traceback (most recent call last):
…
AttributeError:
'tuple' object has no attribute 'sort'
■ >>> atuple = sorted(atuple)
■ >>> atuple
[11, 22, 33]
Tuples are immutable! sorted( )
returns a list!
Most other things work!
■ >>> atuple = (11, 22, 33)
■ >>> len(atuple)
3
■ >>> 44 in atuple
False
■ >>> [ i for [i for i in atuple]
[11, 22, 33]
Converting sequences into tuples
■ >>> alist = [11, 22, 33]
■ >>> atuple = tuple(alist)
■ >>> atuple
(11, 22, 33)
■ >>> newtuple = tuple('Hello World!')
■ >>> newtuple
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!')
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1,2,3) :
print (x, end = ' ')
1 2 3 Iteration
33
T=('C++', 'Java', 'Python)
Python
Expression
Results Description
T[2] 'Python' Offsets start
at zero
T[-2] 'Java' Negative:
count from
the right
T[1:] ('Java',
'Python')
Slicing
fetches
sections
34
S.No. Function & Description
1 cmp(tuple1, tuple2)Compares elements of both tuples.(Not in
Python 3)
2 len(tuple)Gives the total length of the tuple.
3 max(tuple)Returns item from the tuple with max value.
4 min(tuple)Returns item from the tuple with min value.
5 tuple(seq)Converts a list into tuple.
35
Tuples…
#creating Empty tuple
t=tuple()
print(type(t))
t=()
print(type(t))
#initializing tuple
t=(1,)#initialization with single element
t=(1,'ab',56.67,67)
print(t)
#adding two Tuples
s=(1,2,3)+('ab',4)
print(s)
#repetition
print(s*3)
#tuples are immutable--add or modifying not allowed
36
Tuples
#iterating tuples
t=(1,'ab',3,45.67,'bg')
for i in t:
print(i)
for i in range(len(t)):#tuples support integer indexing
print(t[i])
#functions
print(len(t))
t=(23,56,21,67,43)
print(max(t))
print(min(t))
l=[1,2,3]
t=tuple(l)#conversion
print(t)
t=(23,56,21,67,43)
l=sorted(t)
print(l)
#t.sort()--tuples dont have sort functions
l=reversed(t)
37
Sets
38
Method Description
add() Add an element to a set clear() Remove all elements form a set
difference() Return the difference of two or more sets as a new set
difference_update() Remove all elements of another set from this set
Remove an element from set if it is a
discard()
member. (Do nothing if the element is
not in set)
intersection() Return the intersection of two sets as a new set
intersection_update() Update the set with the intersection of itself and another
isdisjoint() Return True if two sets have a null intersection
issubset() Return True if another set contains this set
issuperset() Return True if this set contains another set
39
pop()
remove()
More..
Remove and return an arbitary set
element. Raise KeyErrorif the set is
empty
Remove an element from a set. If the
element is not a member, raise
a KeyError
symmetric_difference() Return the symmetric difference of two sets as a
new set
symmetric_difference_update() Update a set with the symmetric
difference of itself and another
union() Return the union of sets in a new set
update() Update a set with the union of itself and others
40
Built in functions..
Function Description
all() Return True if all elements of the
set are true (or if the set is
empty).
any() Return True if any element of the
set is true. If the set is empty,
return False.
len() Return the length (the number
of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from
elements in the set(does not sort
the set itself).
sum() Retrun the sum of all elements in
the set.
41
Set…
#creating an empty set
s=set()
print(type(s))
s={}#doesn't creates a set --creates empty
dictionary print(type(s))
#initializaton
s={1,11,2,34,23}
s.add(63)
print(s)
#set is not reversible
#s.sort() cant use sort with set
print(sorted(s))#returns a sorted list
s.remove(2)
print(s)
#print(s[1:4])--set is not subscriptable
42
Set…
s={11,22,13,45,34,67,89,'gh'}
p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh'
} t={'gh','hj',66,67}
print(s.union(p,t))
print(s.intersection(p,t))
print(p.difference(s,t))#returns difference between 2 or more
sets
#print(s,p)
s.difference_update(p,t)#updates s with s difference
p,t print(s)
43
Set…
s={11,22,13,45,34,67,89,'gh'}
p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh'
} t={'gh','hj'}
s.update(p,t)#update set s with union of s & p &
t print(s)
s={11,22,13,45,34,67,89}
s.discard(34)#removes element- if not found do
nothing print(s)
#s.remove(34)#removes element if not found raise
error s.discard(34)
s.intersection_update(p)#works with two sets only
#update set element with intersection-returns
None print(s)
44
Set…
s={11,22,13,45,34,67,89}
p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh'
} t={'gh','hj'}
print(s.symmetric_difference(p))#works with two
sets #returns symmetric difference of two sets
print(s)
s.symmetric_difference_update(p)#works with two
sets #updates set s with symmetric difference of s
& p print(s)
45
Set…
s={1,2,3}
p={1,2,3,4,5,6}
t={7,8}
print(s.issubset(p))
print(p.issuperset(s))
print(s.isdisjoint(t))
print(sum(s))
46
Misc…
S={1,2,3}
if all(s):
print("All elements are true")
else:
print("All elements are not true")
s={0,0,23}
if any(s):
print("At least one is true")
else:
print("All are false")
l=[1,2,3]
if all(l):
print("All elements are true")
d={None:0,'ab':None}
if all(d):
print("All elements are true")
else:
print("Not true")
#all and any works with all types
47
Misc…
from copy import copy, deepcopy
l=[1,2,3,['ab','bc']]
t=l
print(t,l,id(t),id(l))
p=copy(l)#shallow copy--copies references in new
objects #therefore ids of elements are same
print(id(p[3]),id(l[3]))#ids same
print(p,l,id(p),id(l))
s=deepcopy(l)#copies elements in new object thereofore ids
different
print(id(s[3]),id(l[3]))#ids different
print(s,l,id(s),id(l))
48

More Related Content

Similar to Session -5for students.pdf

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
 
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
 
Python programming for Beginners - II
Python programming for Beginners - IIPython programming for Beginners - II
Python programming for Beginners - IINEEVEE Technologies
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir1
 
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
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
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 programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in pythonSangita Panchal
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functionsjoellivz
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3Syed Mustafa
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
 

Similar to Session -5for students.pdf (20)

Python.pdf
Python.pdfPython.pdf
Python.pdf
 
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
 
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
 
Python programming for Beginners - II
Python programming for Beginners - IIPython programming for Beginners - II
Python programming for Beginners - II
 
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
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Python lists
Python listsPython lists
Python lists
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 

Recently uploaded

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
 
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
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
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
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
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
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 

Recently uploaded (20)

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
 
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
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
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...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
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
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
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
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
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
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
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
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 

Session -5for students.pdf

  • 1. List, Tuple & Set Session-V
  • 2. 1 Intro to Robots What is a List? ■ An ordered set of values: ■ Ordered: 1st , 2nd , 3rd , … ■ Values: can be anything, integers, strings, other lists ■ List values are called elements. ■ A string is an ordered set of characters so it is “like” a list but not exactly the same thing. Intro to Robots The Empty List x = [ ]
  • 3. ■ The empty list is usually used to initialize a list variable but not give it any useful elements. Intro to Robots Accessing Elements: ■ List elements are accessed via integer indexes starting at 0 and working up. numbers = [ 3, 87, 43] print(numbers[1], numbers[2], numbers[0]) 87 43 3 x = 3 print(numbers[x-2]) 87 print (numbers[1.0]) TypeError: sequence index must be integer print (numbers[3])
  • 4. TypeError: list index out of range print (numbers[-1]) # a negative index counts back 3 # from the end of the list # index -1 is the last element print (numbers[-3]) Intro to Robots Accessing Many Elements: ■ By index value, one at a time (called list traversal) # list of a known size horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’] i = 0 while i < 4: print (horsemen[i]) i = i + 1 # or if you don’t know how long the list is i = 0 length = len(horsemen) while i < length: print( horsemen[i]) i = i + 1
  • 5. war famine pestilence death always safer to use len as an upper bound always I < length; never I <= length Intro to Robots List Membership: ■ You simply ask if a value is “in” or “not in” a list. ■ This is always a True/False question. horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’] if ‘debauchery’ in horseman: print( ‘There are more than 4 horsemen of the apocolipse.) print( ‘debauchery’ not in horsemen) 1 Intro to Robots List Operations: ■ Add two lists:
  • 6. a = [1, 2, 3] b = [4, 5, 6] c = a + b print (c) [1, 2, 3, 4 ,5, 6] ■ Repeat a list many times: a = [1, 2, 3] print (a*3) [1, 2, 3, 1, 2, 3, 1, 2, 3] ■ Exercise: Create a list of 20 zeros. zeros = [0]*20 Intro to Robots List Slices: ■ Sometimes you just want a sub-list (slice) of a list. list[a:b] means
  • 7. list[a], list[a+1], …, list[b-1] # all list elements with indexes from a to b; # including a and excluding b vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] print (vowels[2:4]) [‘i’, ‘o’] # how do you print out the last element? print (vowels[2:]) [‘i’, ‘o’, ‘u’] ■ Exercise: What does vowels[:3] mean? [‘a’, ‘e’, ‘i’] Intro to Robots Lists are Mutable fruit = [‘apple’, ‘orange’, ‘pear’] fruit[1] = ‘fig’ print fruit [‘apple’, ‘fig’, ‘pear’]
  • 8. Intro to Robots List Slices Used to Modify a List: ■ Suppose you are keeping an ordered list: names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] ■ And you want to add kate. Assignment doesn’t work! names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[2] = ‘kate’ print (names) [‘adam’, ‘carol’, ‘kate’, ‘margot’, ‘phil’] ■ You can add an element by squeezing it into an empty slice between two list elements: names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[2:2] = ‘kate’ print (names) [‘adam’, ‘carol’, ‘henry’, ‘kate’, ‘margot’, ‘phil’]
  • 9. Starting at index 2 but not including 2; ie, empty Intro to Robots List Deletion: ■ Using the del operator names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] del names[3] print (names) [‘adam’, ‘carol’, ‘henry’, ‘phil’] ■ Replacing an element with an empty list names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[3:4] = [ ] ■ Deleting slices print (names) [‘adam’, ‘carol’, ‘henry’, ‘phil’] names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] del names[1:4]
  • 10. print (names) [‘adam’, ‘phil’] Intro to Robots Lists, Objects and Values ■ Lists are different: a = [1, 2, 3] b = [1, 2, 3] print( id(a), id(b)) 135023431 135024732 ■ So this time the memory state picture is: a b [1, 2, 3] [1, 2, 3]
  • 11. Intro to Robots Aliasing ■ However, if we assign one variable to another: a = [1, 2, 3] b = a print( id(a), id(b)) 135023431 135023431 ■ So this time the memory state picture is: a [1, 2, 3] b ■ More importantly, changing b also changes a b[0] = 0 print a
  • 12. [0, 2, 3] Intro to Robots Cloning a List: ■ Cloning means making an exact but separate copy: ■ Not Cloning: a = [1, 2, 3] b = a print (id(a), id(b)) 135023431 135023431 ■ Cloning: a = [1, 2, 3] b = a[:] # slices are always separate lists print (id(a), id(b)) 135023431 13502652
  • 14. 15
  • 15. Adding Elements ■ """List are mutable objects represented ■ by []list is an ordered collection""" ■ l=[] ■ print(l) ■ """append adds an item at the end of ■ list""" ■ l.append(9) ■ l.append("hello") ■ l.append(75.2) ■ print(l) ■ """insert adds item at a given ■ index-insert(index,object)""" ■ l.insert(0,90)
  • 16. ■ print(l) 16 Adding Elements ■ l1=[78,23] ■ """extend list by appending ■ elements from object""" ■ l.extend(l1) ■ print(l) ■ l.extend("abc") ■ print(l) ■ l.extend([32,"abc",35.5]) ■ print(l) ■ """append can be used to create ■ nested list"""
  • 17. ■ l1=[34,56] ■ l1.append([23,34]) ■ print(l1) 17 More Operations.. ■ l=[92,56,12,78,1] ■ print(l.count(92)) ■ #sort() the list in increasing order of elements""" ■ l.sort()#doesn’t return object –inplace sorting ■ print(l) ■ #sort(reverse=True sort the list in non increasing order""" ■ l.sort(reverse=True) ■ print(l) ■ l.reverse()
  • 18. ■ print(l) 18 Remove/del ■ l=[23,"bill",67, 89, 90,"abc", "xyz"] ■ """remove searches for an element in list and ■ deletes it""" ■ l.remove("abc") ■ print(l) ■ del(l[2]) ■ print(l) ■ del(l[2:])
  • 19. ■ print(l) ■ l.extend([34,4,67,90]) ■ print(l) ■ #del l[2:4] ■ del(l[:-1]) ■ print(l) ■ del l[:]#removes all elements but not list ■ print(l) ■ """delete list""" ■ del l ■ print(l)#NameError: name 'l' not defined 19 Index/pop ■ l=["abc",30,50] ■ x=l.index(30) ■ print(x) ■ """pop function by default removes last element
  • 20. ■ --pop(index)""" ■ numbers.pop() ■ print(numbers) ■ x=numbers.pop(0) ■ print(numbers) ■ x=len(numbers) ■ print(x) ■ x=max(numbers) ■ print(x) ■ x=min(numbers) ■ print(x) 20 Sorted ■ l=[5,4,3,2,1] ■ p=sorted(l)
  • 22. ■ l=array('i') ■ l.append(90) ■ l.append(40) ■ print(l) ■ #l.append(53.25) ■ print(l) ■ l[0]=100 ■ print(l)
  • 23. 22 More… ■ s=array('u',"hello") ■ print(s) ■ for ch in s: ■ print(ch) ■ s.reverse() ■ print(s)
  • 24. ■ s.pop() ■ print(s) ■ s.index("l") ■ x=sorted(s) ■ print(x) ■ p=array('i') ■ for x in range(1,6): ■ p.append(x) ■ print(p) 23 typecodes
  • 25. 24
  • 26. Tuples ■ Same as lists but ■ Immutable ■ Enclosed in parentheses ■ A tuple with a single element must have a comma inside the parentheses: ■ a = (11,) Examples ■ >>> mytuple = (11, 22, 33) ■ >>> mytuple[0] 11 ■ >>> mytuple[-1] 33 ■ >>> mytuple[0:1] (11,)
  • 27. ■ The comma is required! Why? ■ No confusion possible between [11] and 11 ■ (11) is a perfectly acceptable expression ■ (11) without the comma is the integer 11 ■ (11, ) with the comma is a tuple containing the integer 11 Tuples are immutable ■ >>> mytuple = (11, 22, 33) ■ >>> saved = mytuple ■ >>> mytuple += (44,) ■ >>> mytuple (11, 22, 33, 44) ■ >>> saved
  • 28. (11, 22, 33) Things that do not work ■ mytuple += 55 Traceback (most recent call last):Z … TypeError: can only concatenate tuple (not "int") to tuple ■ Can understand that! Sorting tuples ■ >>> atuple = (33, 22, 11) ■ >>> atuple.sort() Traceback (most recent call last):
  • 29. … AttributeError: 'tuple' object has no attribute 'sort' ■ >>> atuple = sorted(atuple) ■ >>> atuple [11, 22, 33] Tuples are immutable! sorted( ) returns a list! Most other things work! ■ >>> atuple = (11, 22, 33)
  • 30. ■ >>> len(atuple) 3 ■ >>> 44 in atuple False ■ >>> [ i for [i for i in atuple] [11, 22, 33] Converting sequences into tuples ■ >>> alist = [11, 22, 33] ■ >>> atuple = tuple(alist) ■ >>> atuple (11, 22, 33) ■ >>> newtuple = tuple('Hello World!') ■ >>> newtuple ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!') Python Expression Results Description
  • 31. len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1, 2, 3) True Membership for x in (1,2,3) : print (x, end = ' ') 1 2 3 Iteration 33 T=('C++', 'Java', 'Python) Python Expression Results Description T[2] 'Python' Offsets start at zero T[-2] 'Java' Negative: count from the right
  • 32. T[1:] ('Java', 'Python') Slicing fetches sections 34 S.No. Function & Description 1 cmp(tuple1, tuple2)Compares elements of both tuples.(Not in Python 3) 2 len(tuple)Gives the total length of the tuple. 3 max(tuple)Returns item from the tuple with max value. 4 min(tuple)Returns item from the tuple with min value.
  • 33. 5 tuple(seq)Converts a list into tuple. 35 Tuples… #creating Empty tuple t=tuple() print(type(t)) t=() print(type(t)) #initializing tuple t=(1,)#initialization with single element t=(1,'ab',56.67,67) print(t) #adding two Tuples
  • 34. s=(1,2,3)+('ab',4) print(s) #repetition print(s*3) #tuples are immutable--add or modifying not allowed 36 Tuples #iterating tuples t=(1,'ab',3,45.67,'bg') for i in t: print(i) for i in range(len(t)):#tuples support integer indexing print(t[i]) #functions print(len(t)) t=(23,56,21,67,43)
  • 36. Sets 38 Method Description add() Add an element to a set clear() Remove all elements form a set difference() Return the difference of two or more sets as a new set difference_update() Remove all elements of another set from this set
  • 37. Remove an element from set if it is a discard() member. (Do nothing if the element is not in set) intersection() Return the intersection of two sets as a new set intersection_update() Update the set with the intersection of itself and another isdisjoint() Return True if two sets have a null intersection issubset() Return True if another set contains this set issuperset() Return True if this set contains another set 39 pop() remove() More..
  • 38. Remove and return an arbitary set element. Raise KeyErrorif the set is empty Remove an element from a set. If the element is not a member, raise a KeyError symmetric_difference() Return the symmetric difference of two sets as a new set symmetric_difference_update() Update a set with the symmetric difference of itself and another union() Return the union of sets in a new set update() Update a set with the union of itself and others 40
  • 39. Built in functions.. Function Description all() Return True if all elements of the set are true (or if the set is empty). any() Return True if any element of the set is true. If the set is empty, return False. len() Return the length (the number of items) in the set. max() Return the largest item in the set. min() Return the smallest item in the set. sorted() Return a new sorted list from elements in the set(does not sort the set itself).
  • 40. sum() Retrun the sum of all elements in the set. 41 Set… #creating an empty set s=set() print(type(s)) s={}#doesn't creates a set --creates empty dictionary print(type(s)) #initializaton s={1,11,2,34,23} s.add(63) print(s) #set is not reversible
  • 41. #s.sort() cant use sort with set print(sorted(s))#returns a sorted list s.remove(2) print(s) #print(s[1:4])--set is not subscriptable 42 Set… s={11,22,13,45,34,67,89,'gh'} p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh' } t={'gh','hj',66,67} print(s.union(p,t)) print(s.intersection(p,t)) print(p.difference(s,t))#returns difference between 2 or more sets #print(s,p)
  • 42. s.difference_update(p,t)#updates s with s difference p,t print(s) 43 Set… s={11,22,13,45,34,67,89,'gh'} p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh' } t={'gh','hj'} s.update(p,t)#update set s with union of s & p & t print(s)
  • 43. s={11,22,13,45,34,67,89} s.discard(34)#removes element- if not found do nothing print(s) #s.remove(34)#removes element if not found raise error s.discard(34) s.intersection_update(p)#works with two sets only #update set element with intersection-returns None print(s) 44 Set… s={11,22,13,45,34,67,89} p={98,23,13,66,45,89,'jhon',56.78,56,32,'ab','gh' } t={'gh','hj'}
  • 44. print(s.symmetric_difference(p))#works with two sets #returns symmetric difference of two sets print(s) s.symmetric_difference_update(p)#works with two sets #updates set s with symmetric difference of s & p print(s) 45 Set… s={1,2,3}
  • 46. Misc… S={1,2,3} if all(s): print("All elements are true") else: print("All elements are not true") s={0,0,23} if any(s): print("At least one is true") else: print("All are false") l=[1,2,3] if all(l): print("All elements are true") d={None:0,'ab':None} if all(d): print("All elements are true") else:
  • 47. print("Not true") #all and any works with all types 47 Misc… from copy import copy, deepcopy l=[1,2,3,['ab','bc']] t=l print(t,l,id(t),id(l)) p=copy(l)#shallow copy--copies references in new objects #therefore ids of elements are same print(id(p[3]),id(l[3]))#ids same print(p,l,id(p),id(l)) s=deepcopy(l)#copies elements in new object thereofore ids different print(id(s[3]),id(l[3]))#ids different