SlideShare a Scribd company logo
1 of 22
Download to read offline
Introduction to Python

          Lecture 4
       Kasyanov Anton



          IASA 2011
Plan

   Lists
   Tuples
   Dictionaries
Lists

   Python has a way of grouping similar items
    called a list.
   Denoted by:
    list_name =
    [list_elt0,list_elt1, ...,
    list_eltn]
Lists

   To get to the i-th element of a list we use:
    list_name[i-1]
   We use i-1 because lists are indexed from 0.
   This means to refer to the elements of a 4
    element list named list_name we use
    list_name[0], list_name[1],
    list_name[2], list_name[3]
   Lists are mutable.
Lists

   You can also have an empty list: [].
   You can index into lists from the back.
   list_name[-i] returns the ith element from the
    back.
   Lists are mixed:
       That is, the elements in a list need not be the same
        type, can have ints and strings.
       Can even have lists themselves.
   + and * operators are overloaded for lists
Functions

   Lists come with lots of useful functions and
    methods.
   len(list_name), as with strings, returns the
    length of the list.
   min(list_name) and max(list_name)
    return the min and max so long as the list is
    well defined.
   sum(list_name) returns the sum of elements
    so long as they're numbered.
       Not defined for lists of strings.
Methods

   append(value) – adds the value to the end
    of the list.
   sort() - sorts the list so long as this is well
    defined. (need consistent notions of > and ==)
   insert(index, value) – inserts the
    element value at the index specified.
   remove(value) – removes the first instance
    of value.
   count(value) – counts the number of
    instances of value in the list.
Looping

   Often we want to do a similar operation to every
    element of the list.
   Python allows us to do this using for loops.
      for item in list:
              block
   This is equivalent to:
      item = list[0]
      block
      item = list [1]
      block
      ...
Looping

   To do that, we use the range() function.
       range(i) returns an ordered list of ints ranging
        from 0 to i-1.
       range(i,j) returns an ordered list of ints ranging
        from i to j-1 inclusive.
       range(i,j,k) returns a list of ints ranging from i
        to j-1 with a step of at least k between ints.
   So range(i,k)==range(i,k,1)
   To modify a list element by element we use:
        for i in range(len(list)):
                 list[i] = ...
Slicing

   Sometimes we want to perform operations on a
    sublist.
   To refer to a sublist we use list slicing.
   y=x[i:j] gives us a list y with the elements
    from i to j-1 inclusive.
       x[:] makes a list that contains all the elements of the original.
       x[i:] makes a list that contains the elements from i to the end.
       x[:j] makes a list that contains the elements from the beginning
        to j-1.
Tuples

   Sometimes we want our lists to be immutable.
   To do that we can make a tuple.
   tuple_name=(item0,item1,item2,...)
       Items are referenced by tuple_name[i] not
        tuple_name(i)
       Single element tuples must be defined with a
        comma to avoid ambiguity
                   (8+3) vs. (8+3,)
Strings

   Strings can be considered tuples of individual
    characters. (since they are immutable).
   In particular, this means that we can use the list
    knowledge that we gained, an apply it to
    strings.
       Can reference individual characters by string[+/-i].
       Strings are not mixed, they can only contain
        characters.
       min() and max() defined on strings, but sum() is not.
       You can slice strings just as you can lists.
Strings

   Now that we know that we can index into
    strings, we can look at some more string
    methods.
       find(substring): give the index of the first character
        in a matching the substring from the left or -1 if no
        such character exists.
       rfind(substring): same as above, but from the right.
       find(substring,i,j): same as find(), but looks only in
        string[i:j].
Nested lists

   Because lists are mixed, we can have lists of
    lists.
   This is useful if we want matrices, or to
    represent a grid or higher dimensional space.
   We then reference elements by list_name[i][j] if
    we want the jth element of the ith list.
   So then naturally, if we wish to loop over all the
    elements we need nested loops:
               for item in list_name:
                   for item2 in item:
                       block
Dictionaries

   In one sentence, dictionaries are (key, value)
    pairs. Sometimes they are called maps.
   Python syntax:
        {key0 : value0, key1 : value1, ...,
        keyn : valuen}
   Dictionaries are of type dict
       Since they have a type, they can be assigned to a
        variable.
   To refer to a value associated with a key in a
    dictionary we use dictionary_name[key]
Dictionaries

   Dictionaries are unsorted.
   Dictionary keys must be immutable, but the
    values can be anything.
       Cannot be None.
   Once you've created a dictionary you can add
    key-value pairs by assigning the value to the
    key.
        dictionary_name[key] = value
   Keys must be unique.
Dictionary methods
   len(dict_name) works in the same way as it
    does for strings and lists.
   + and * are not defined for dictionaries.
   dict.keys() - returns the keys in some
    order.
   dict.values() - returns the values in some
    order.
   dict.items() - returns the (key, value) pairs
    in some order.
       All of these methods have iter* variants that return
        the keys|values|key-value pairs one by one.
Dictionary methods

   dict.has_key(key) - returns True iff the
    dictionary has the key in it.
   dict.get(key) – returns the value that is
    paired with the key, or None if no such key
    exists.
       get(key, d) returns d rather than None if no
        such key exists.
   dict.clear() - removes all the key-value
    pairs from the dictionary.
Files

   How to read file line by line
       File = open(filename)
       For line in file.readlines():
          Print line
Home assignment

   You have to create a simple dictionary
    program.
   Dictionary in file:
       Home=дом
       Table=стол
       Etc.
   Program have to translate words from one
    language to another and vice versa.
Home assignment

   Any other improvements are welcome
   Use modules if you want
   Use str.split() and list.index() functions
   Create two versions:
       Using lists
       Using dicts
   Send files to mind_master@ukr.net due to
    Monday
Anton Kasyanov, Introduction to Python, Lecture4

More Related Content

What's hot

Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Python Collections
Python CollectionsPython Collections
Python Collectionssachingarg0
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)Ali ٍSattar
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Pythonyashar Aliabasi
 
Python data type
Python data typePython data type
Python data typenuripatidar
 
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 pythonchanna basava
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09Terry Yoast
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 

What's hot (19)

Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Python data type
Python data typePython data type
Python data type
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
Python data type
Python data typePython data type
Python data type
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Groovy
GroovyGroovy
Groovy
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
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
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
Python strings
Python stringsPython strings
Python strings
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python list
Python listPython list
Python list
 

Similar to Anton Kasyanov, Introduction to Python, Lecture4

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfMCCMOTOR
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningTURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat SheetVerxus
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfElNew2
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
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
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge O T
 
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxPYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxsurajnath20
 
Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfalivaisi1
 
Beginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfBeginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfAkhileshKumar436707
 
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
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docxmanohar25689
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 

Similar to Anton Kasyanov, Introduction to Python, Lecture4 (20)

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
 
dataStructuresInPython.pptx
dataStructuresInPython.pptxdataStructuresInPython.pptx
dataStructuresInPython.pptx
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.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
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
 
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxPYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
 
Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdf
 
Beginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfBeginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdf
 
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
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 

More from Anton Kasyanov

spaCy lightning talk for KyivPy #21
spaCy lightning talk for KyivPy #21spaCy lightning talk for KyivPy #21
spaCy lightning talk for KyivPy #21Anton Kasyanov
 
Introduction to Computer Vision (uapycon 2017)
Introduction to Computer Vision (uapycon 2017)Introduction to Computer Vision (uapycon 2017)
Introduction to Computer Vision (uapycon 2017)Anton Kasyanov
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
 
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3Anton Kasyanov
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov
 
Anton Kasyanov, Introduction to Python, Lecture1
Anton Kasyanov, Introduction to Python, Lecture1Anton Kasyanov, Introduction to Python, Lecture1
Anton Kasyanov, Introduction to Python, Lecture1Anton Kasyanov
 

More from Anton Kasyanov (7)

spaCy lightning talk for KyivPy #21
spaCy lightning talk for KyivPy #21spaCy lightning talk for KyivPy #21
spaCy lightning talk for KyivPy #21
 
Introduction to Computer Vision (uapycon 2017)
Introduction to Computer Vision (uapycon 2017)Introduction to Computer Vision (uapycon 2017)
Introduction to Computer Vision (uapycon 2017)
 
aiohttp intro
aiohttp introaiohttp intro
aiohttp intro
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2
 
Anton Kasyanov, Introduction to Python, Lecture1
Anton Kasyanov, Introduction to Python, Lecture1Anton Kasyanov, Introduction to Python, Lecture1
Anton Kasyanov, Introduction to Python, Lecture1
 

Anton Kasyanov, Introduction to Python, Lecture4

  • 1. Introduction to Python Lecture 4 Kasyanov Anton IASA 2011
  • 2. Plan  Lists  Tuples  Dictionaries
  • 3. Lists  Python has a way of grouping similar items called a list.  Denoted by: list_name = [list_elt0,list_elt1, ..., list_eltn]
  • 4. Lists  To get to the i-th element of a list we use: list_name[i-1]  We use i-1 because lists are indexed from 0.  This means to refer to the elements of a 4 element list named list_name we use list_name[0], list_name[1], list_name[2], list_name[3]  Lists are mutable.
  • 5. Lists  You can also have an empty list: [].  You can index into lists from the back.  list_name[-i] returns the ith element from the back.  Lists are mixed:  That is, the elements in a list need not be the same type, can have ints and strings.  Can even have lists themselves.  + and * operators are overloaded for lists
  • 6. Functions  Lists come with lots of useful functions and methods.  len(list_name), as with strings, returns the length of the list.  min(list_name) and max(list_name) return the min and max so long as the list is well defined.  sum(list_name) returns the sum of elements so long as they're numbered.  Not defined for lists of strings.
  • 7. Methods  append(value) – adds the value to the end of the list.  sort() - sorts the list so long as this is well defined. (need consistent notions of > and ==)  insert(index, value) – inserts the element value at the index specified.  remove(value) – removes the first instance of value.  count(value) – counts the number of instances of value in the list.
  • 8. Looping  Often we want to do a similar operation to every element of the list.  Python allows us to do this using for loops. for item in list: block  This is equivalent to: item = list[0] block item = list [1] block ...
  • 9. Looping  To do that, we use the range() function.  range(i) returns an ordered list of ints ranging from 0 to i-1.  range(i,j) returns an ordered list of ints ranging from i to j-1 inclusive.  range(i,j,k) returns a list of ints ranging from i to j-1 with a step of at least k between ints.  So range(i,k)==range(i,k,1)  To modify a list element by element we use: for i in range(len(list)): list[i] = ...
  • 10. Slicing  Sometimes we want to perform operations on a sublist.  To refer to a sublist we use list slicing.  y=x[i:j] gives us a list y with the elements from i to j-1 inclusive.  x[:] makes a list that contains all the elements of the original.  x[i:] makes a list that contains the elements from i to the end.  x[:j] makes a list that contains the elements from the beginning to j-1.
  • 11. Tuples  Sometimes we want our lists to be immutable.  To do that we can make a tuple.  tuple_name=(item0,item1,item2,...)  Items are referenced by tuple_name[i] not tuple_name(i)  Single element tuples must be defined with a comma to avoid ambiguity  (8+3) vs. (8+3,)
  • 12. Strings  Strings can be considered tuples of individual characters. (since they are immutable).  In particular, this means that we can use the list knowledge that we gained, an apply it to strings.  Can reference individual characters by string[+/-i].  Strings are not mixed, they can only contain characters.  min() and max() defined on strings, but sum() is not.  You can slice strings just as you can lists.
  • 13. Strings  Now that we know that we can index into strings, we can look at some more string methods.  find(substring): give the index of the first character in a matching the substring from the left or -1 if no such character exists.  rfind(substring): same as above, but from the right.  find(substring,i,j): same as find(), but looks only in string[i:j].
  • 14. Nested lists  Because lists are mixed, we can have lists of lists.  This is useful if we want matrices, or to represent a grid or higher dimensional space.  We then reference elements by list_name[i][j] if we want the jth element of the ith list.  So then naturally, if we wish to loop over all the elements we need nested loops: for item in list_name: for item2 in item: block
  • 15. Dictionaries  In one sentence, dictionaries are (key, value) pairs. Sometimes they are called maps.  Python syntax: {key0 : value0, key1 : value1, ..., keyn : valuen}  Dictionaries are of type dict  Since they have a type, they can be assigned to a variable.  To refer to a value associated with a key in a dictionary we use dictionary_name[key]
  • 16. Dictionaries  Dictionaries are unsorted.  Dictionary keys must be immutable, but the values can be anything.  Cannot be None.  Once you've created a dictionary you can add key-value pairs by assigning the value to the key. dictionary_name[key] = value  Keys must be unique.
  • 17. Dictionary methods  len(dict_name) works in the same way as it does for strings and lists.  + and * are not defined for dictionaries.  dict.keys() - returns the keys in some order.  dict.values() - returns the values in some order.  dict.items() - returns the (key, value) pairs in some order.  All of these methods have iter* variants that return the keys|values|key-value pairs one by one.
  • 18. Dictionary methods  dict.has_key(key) - returns True iff the dictionary has the key in it.  dict.get(key) – returns the value that is paired with the key, or None if no such key exists.  get(key, d) returns d rather than None if no such key exists.  dict.clear() - removes all the key-value pairs from the dictionary.
  • 19. Files  How to read file line by line  File = open(filename)  For line in file.readlines():  Print line
  • 20. Home assignment  You have to create a simple dictionary program.  Dictionary in file:  Home=дом  Table=стол  Etc.  Program have to translate words from one language to another and vice versa.
  • 21. Home assignment  Any other improvements are welcome  Use modules if you want  Use str.split() and list.index() functions  Create two versions:  Using lists  Using dicts  Send files to mind_master@ukr.net due to Monday