SlideShare a Scribd company logo
Advanced Data Structures

    Lists
●

    Tuples
●

    Sets
●

    Dictionaries
●
Introduction to lists

Python knows a number of compound data
types, used to group together other values. The
most versatile is the list, which can be written as
a list of comma-separated values (items)
between square brackets. List items need not
all have the same type.
>>> a = [100,200,300,400,500]
>>> a
[100,200,300,400,500]

Can be accessed with index values like arrays
in C/C++/Java.

>>> a[0]
100

Access the 2nd element from the end of the list
>>> a[-2]
400
Slicing: Extract values from the list within a
given index range.
                   nd
For eg. from the 2 element of the given list to
the last but one element.

>>> a[1:-1]
[200, 300, 400]
Some special cases

listobject[:x]
      If x is a positive value, then x number of entries
  –
      from the beginning of the list would be sliced
      >>a[:3]
      [100, 200, 300]

      If x is a negative value, for eg -2, then all the
  –
      entries from the list except the last 2 would be
      sliced
        >>> a[:-2]
       [100, 200, 300]
Some special cases(contd...)
listobject[x:]
      If x is positive, all the entries except for the first x
  –
      entries would be sliced
      >>> a[2:]
      [300, 400, 500]

      If x is negative, for eg -2, then 2 entries from the
  –
      end of the list would be sliced
      >>> a[-2:]
      [400, 500]
Assignment to slices is also possible, and this
can even change the size of the list or clear it
entirely

>>> a[0:2] = [1, 12]
>>> a
[1, 12, 300, 400, 500]

Removing a slice
>>> a[0:2] = []
>>> a
[300, 400, 500]
Assignment to slices (special case)

You can empty the whole list with

>>> a[:] = []
>>> a
[]
Nesting lists

>>>   q=[2,3]
>>>   p=[1,q,4]
>>>   p
[1,   [2, 3], 4]


>>> p[1]
[2, 3]
Methods of the list data type

 list.append(x)
●


Add an item to the end of the list

  list.extend(L)
●


Extend the list by appending all the items in the
given list
list.insert(i, x)
●

Insert an item at a given position. The first argument
is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and
a.insert(len(a), x) is equivalent to a.append(x)

    list.remove(x)
●

Remove the first item from the list whose value is x.
It is an error if there is no such item.

    list.index(x)
●

Return the index in the list of the first item whose
value is x. It is an error if there is no such item.
list.pop([i])
●

Remove the item at the given position in the list, and
return it. If no index is specified, a.pop() removes
and returns the last item in the list

    list.count(x)
●

Return the number of times x appears in the list.

    list.sort()
●


    list.reverse()
●
Another way to remove entries from a list is
●

    the use of the del statement

>>>   a = [-1, 1, 66.25, 333, 333, 1234.5]
>>>   del a[0]
>>>   a
[1,   66.25, 333, 333, 1234.5]
>>>   del a[2:4]
>>>   a
[1,   66.25, 1234.5]
>>>   del a[:]
>>>   a
[]
Tuples
A tuple consists of a number of values
separated by commas, for instance:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>>u = t, (1, 2, 3, 4, 5) # Tuples may
  be nested
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4,
  5))
Construct a single element tuple
●




>>> singleton = 'hello',
# note trailing comma
>>> singleton
('hello',)

The statement t = 12345,54321,'hello!'
is an example of tuple packing
Sequence unpacking
●




Sequence unpacking requires the list of
variables on the left to have the same number of
elements as the length of the sequence

>>> x, y, z = t
Sets
A set is an unordered collection with no
duplicate elements. Set objects also support
mathematical operations like union,
intersection, difference, and symmetric
difference.
>>> basket = ['apple', 'orange', 'apple',
  'pear', 'orange', 'banana']
>>> fruit = set(basket)
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])

# fast membership testing
>>> 'orange' in fruit
True
>>> 'crabgrass' in fruit
False
Set operations on unique letters from two words

>>> a = set('abracadabra')
>>> b = set('alacazam')

# unique letters in a
>>> a
set(['a', 'r', 'b', 'c', 'd'])

# letters in a but not in b
>>> a - b
set(['r', 'd', 'b'])
# letters in either a or b
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z',
  'l'])

# letters in both a and b
>>> a & b
set(['a', 'c'])

# letters in a or b but not both
>>> a ^ b
set(['r', 'd', 'b', 'm', 'z', 'l'])
Dictionaries
Unordered set of key: value pairs, with the
requirement that the keys are unique (within
one dictionary)

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack':
  4098}
The keys() method of the dictionary data type
returns a list of the keys.

>>> tel.keys()
['sape', 'jack', 'guido']

Both keys and values can either be strings or
numbers.
Build a dictionary from key-value pairs stored
●

    as tuples

>>> dict([('sape', 4139), ('guido',
  4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido':
  4127}

Note the dict() constructor
Looping techniques
Use the iteritems() method to loop through
dictionaries

>>> knights = {’gallahad’: ’the pure’,
  ’robin’: ’the brave’}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave
Looping over two sequences at the
same time
Use the zip() method

>>> a =   ['foo','bar']
>>> b =   [42, 0]
>>> for   i,j in zip(a,b):
...       print quot;%s:%dquot; % (i,j)
...
foo:42
bar:0
File objects
    Quick introduction to file handling
●




open() returns a file object, and is most commonly
used with two arguments: ‘open(filename, mode)’

>>> f = open('temp.txt','w')
>>> f
<open file 'temp.txt', mode 'w' at
0xb7d4c5c0>
'r'
●

The file must already exist, and it is opened in
read-only mode.

  'w'
●

The file is opened in write-only mode. The file is
truncated and overwritten if it already exists, or
created if it does not exist.
'a'
●

The file is opened in write-only mode. The file is
kept intact if it already exists, and the data you
write is appended to what's already in the file.
The file is created if it does not exist.

 'r+'
●

The file must already exist and is opened for
both reading and writing, so all methods of f can
be called .
'w+'
●

The file is opened for both reading and writing,
so all methods of f can be called. The file is
truncated and overwritten if it already exists, or
created if it does not exist.

  'a+'
●

The file is opened for both reading and writing,
so all methods of f can be called. The file is kept
intact if it already exists, and the data you write
is appended to what's already in the file. The
  file
is created if it does not exist.
Reading from a file object
●




f.read(size)

The size is an optional argument, which when
specified reads that many bytes at most. If
nothing is specified, it reads the contents of the
whole file and returns it as a string.
f.readline()

Reads a line from the file, returns it as a string
and moves on to the next line.

f.readlines()

This returns a list of all the lines in the file. Can
be used to loop through the contents of a file.
For eg

>>>for line in f.readlines():
... print line
...
Writing to a file
●




f.write(string)

It's simple!

    Closing the file object
●




f.close()

Close the file and free up system resources
being used by the file object.
A few important string functions

 s.split()
●


Splits a string consisting of words seperated by
whitespaces and returns a list of the words.

  s.rstrip()
●


Remove whitespaces from the leading end or
the right side

    s.lstrip()
●
Exceptions


Errors detected during execution are called
exceptions and are not unconditionally fatal.
Handling exceptions
Overall structure....

try:
        #code that may cause runtime
        #error
except [errortype]:
        #handle the error
[else:]
        #do something if no error raised
[finally:]
        #irrespective of error being
        #raised or not do something
>>> while True:
...   try:
...     x = int(raw_input(quot;enter a
number: quot;))
...     break
...   except ValueError:
...     print quot;Oops!quot;
...
Raising exceptions
●




>>> raise NameError, ’HiThere’
Traceback (most recent call last):
  File quot;<stdin>quot;, line 1, in ?
NameError: HiThere

Try this: Accept two numbers, raise a
ValueError when division by 0 is attempted and
handle it too

More Related Content

What's hot

Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
P3 InfoTech Solutions Pvt. Ltd.
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Python Collections
Python CollectionsPython Collections
Python Collections
sachingarg0
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
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
channa basava
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
Python : Functions
Python : FunctionsPython : Functions
Python Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptxPython Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptx
ShreyasLawand
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Arrays
ArraysArrays
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 

What's hot (20)

Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
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
 
Sets in python
Sets in pythonSets in python
Sets in python
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Python Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptxPython Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptx
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
2D Array
2D Array 2D Array
2D Array
 
Arrays
ArraysArrays
Arrays
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 

Viewers also liked

Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
Tuples
TuplesTuples
Slicing
SlicingSlicing
Python002
Python002Python002
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
Blue Elephant Consulting
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
Nowell Strite
 

Viewers also liked (8)

Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 
Tuples
TuplesTuples
Tuples
 
Slicing
SlicingSlicing
Slicing
 
Python002
Python002Python002
Python002
 
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
 
Lists
ListsLists
Lists
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Python Workshop Part 2. LUG Maniapl

Intro python
Intro pythonIntro python
Intro pythonkamzilla
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
frankieroberto
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
Karin Lagesen
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
amiable_indian
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
MihirDatir
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
saniac
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
feelinggift
 
Prototype js
Prototype jsPrototype js
Prototype js
mussawir20
 
Chapter03
Chapter03Chapter03
Chapter03
春男 洪
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
David Pollak
 

Similar to Python Workshop Part 2. LUG Maniapl (20)

Intro python
Intro pythonIntro python
Intro python
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
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 Workshop
Python  Workshop Python  Workshop
Python Workshop
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
 
Prototype js
Prototype jsPrototype js
Prototype js
 
Chapter03
Chapter03Chapter03
Chapter03
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 

Python Workshop Part 2. LUG Maniapl

  • 1. Advanced Data Structures Lists ● Tuples ● Sets ● Dictionaries ●
  • 2. Introduction to lists Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.
  • 3. >>> a = [100,200,300,400,500] >>> a [100,200,300,400,500] Can be accessed with index values like arrays in C/C++/Java. >>> a[0] 100 Access the 2nd element from the end of the list >>> a[-2] 400
  • 4. Slicing: Extract values from the list within a given index range. nd For eg. from the 2 element of the given list to the last but one element. >>> a[1:-1] [200, 300, 400]
  • 5. Some special cases listobject[:x] If x is a positive value, then x number of entries – from the beginning of the list would be sliced >>a[:3] [100, 200, 300] If x is a negative value, for eg -2, then all the – entries from the list except the last 2 would be sliced >>> a[:-2] [100, 200, 300]
  • 6. Some special cases(contd...) listobject[x:] If x is positive, all the entries except for the first x – entries would be sliced >>> a[2:] [300, 400, 500] If x is negative, for eg -2, then 2 entries from the – end of the list would be sliced >>> a[-2:] [400, 500]
  • 7. Assignment to slices is also possible, and this can even change the size of the list or clear it entirely >>> a[0:2] = [1, 12] >>> a [1, 12, 300, 400, 500] Removing a slice >>> a[0:2] = [] >>> a [300, 400, 500]
  • 8. Assignment to slices (special case) You can empty the whole list with >>> a[:] = [] >>> a []
  • 9. Nesting lists >>> q=[2,3] >>> p=[1,q,4] >>> p [1, [2, 3], 4] >>> p[1] [2, 3]
  • 10. Methods of the list data type list.append(x) ● Add an item to the end of the list list.extend(L) ● Extend the list by appending all the items in the given list
  • 11. list.insert(i, x) ● Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) list.remove(x) ● Remove the first item from the list whose value is x. It is an error if there is no such item. list.index(x) ● Return the index in the list of the first item whose value is x. It is an error if there is no such item.
  • 12. list.pop([i]) ● Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list list.count(x) ● Return the number of times x appears in the list. list.sort() ● list.reverse() ●
  • 13. Another way to remove entries from a list is ● the use of the del statement >>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a []
  • 14. Tuples A tuple consists of a number of values separated by commas, for instance: >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>>u = t, (1, 2, 3, 4, 5) # Tuples may be nested >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
  • 15. Construct a single element tuple ● >>> singleton = 'hello', # note trailing comma >>> singleton ('hello',) The statement t = 12345,54321,'hello!' is an example of tuple packing
  • 16. Sequence unpacking ● Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence >>> x, y, z = t
  • 17. Sets A set is an unordered collection with no duplicate elements. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
  • 18. >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) >>> fruit set(['orange', 'pear', 'apple', 'banana']) # fast membership testing >>> 'orange' in fruit True >>> 'crabgrass' in fruit False
  • 19. Set operations on unique letters from two words >>> a = set('abracadabra') >>> b = set('alacazam') # unique letters in a >>> a set(['a', 'r', 'b', 'c', 'd']) # letters in a but not in b >>> a - b set(['r', 'd', 'b'])
  • 20. # letters in either a or b >>> a | b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) # letters in both a and b >>> a & b set(['a', 'c']) # letters in a or b but not both >>> a ^ b set(['r', 'd', 'b', 'm', 'z', 'l'])
  • 21. Dictionaries Unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary) >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098}
  • 22. The keys() method of the dictionary data type returns a list of the keys. >>> tel.keys() ['sape', 'jack', 'guido'] Both keys and values can either be strings or numbers.
  • 23. Build a dictionary from key-value pairs stored ● as tuples >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127} Note the dict() constructor
  • 24. Looping techniques Use the iteritems() method to loop through dictionaries >>> knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’} >>> for k, v in knights.iteritems(): ... print k, v ... gallahad the pure robin the brave
  • 25. Looping over two sequences at the same time Use the zip() method >>> a = ['foo','bar'] >>> b = [42, 0] >>> for i,j in zip(a,b): ... print quot;%s:%dquot; % (i,j) ... foo:42 bar:0
  • 26. File objects Quick introduction to file handling ● open() returns a file object, and is most commonly used with two arguments: ‘open(filename, mode)’ >>> f = open('temp.txt','w') >>> f <open file 'temp.txt', mode 'w' at 0xb7d4c5c0>
  • 27. 'r' ● The file must already exist, and it is opened in read-only mode. 'w' ● The file is opened in write-only mode. The file is truncated and overwritten if it already exists, or created if it does not exist.
  • 28. 'a' ● The file is opened in write-only mode. The file is kept intact if it already exists, and the data you write is appended to what's already in the file. The file is created if it does not exist. 'r+' ● The file must already exist and is opened for both reading and writing, so all methods of f can be called .
  • 29. 'w+' ● The file is opened for both reading and writing, so all methods of f can be called. The file is truncated and overwritten if it already exists, or created if it does not exist. 'a+' ● The file is opened for both reading and writing, so all methods of f can be called. The file is kept intact if it already exists, and the data you write is appended to what's already in the file. The file is created if it does not exist.
  • 30. Reading from a file object ● f.read(size) The size is an optional argument, which when specified reads that many bytes at most. If nothing is specified, it reads the contents of the whole file and returns it as a string.
  • 31. f.readline() Reads a line from the file, returns it as a string and moves on to the next line. f.readlines() This returns a list of all the lines in the file. Can be used to loop through the contents of a file. For eg >>>for line in f.readlines(): ... print line ...
  • 32. Writing to a file ● f.write(string) It's simple! Closing the file object ● f.close() Close the file and free up system resources being used by the file object.
  • 33. A few important string functions s.split() ● Splits a string consisting of words seperated by whitespaces and returns a list of the words. s.rstrip() ● Remove whitespaces from the leading end or the right side s.lstrip() ●
  • 34. Exceptions Errors detected during execution are called exceptions and are not unconditionally fatal.
  • 35. Handling exceptions Overall structure.... try: #code that may cause runtime #error except [errortype]: #handle the error [else:] #do something if no error raised [finally:] #irrespective of error being #raised or not do something
  • 36. >>> while True: ... try: ... x = int(raw_input(quot;enter a number: quot;)) ... break ... except ValueError: ... print quot;Oops!quot; ...
  • 37. Raising exceptions ● >>> raise NameError, ’HiThere’ Traceback (most recent call last): File quot;<stdin>quot;, line 1, in ? NameError: HiThere Try this: Accept two numbers, raise a ValueError when division by 0 is attempted and handle it too