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

PDF
Python :variable types
PPTX
Values and Data types in python
PPTX
Data Structures in Python
PPTX
Basic data structures in python
PPTX
Data structures in Python
PDF
Datatypes in python
PDF
1. python
PDF
Python-03| Data types
Python :variable types
Values and Data types in python
Data Structures in Python
Basic data structures in python
Data structures in Python
Datatypes in python
1. python
Python-03| Data types

What's hot (19)

PPT
Strings Arrays
PPTX
Python Collections
PPTX
Python data type
PPTX
Data types in python
PPTX
Python dictionary
PPTX
Data types in python lecture (2)
PPTX
An Introduction to Tuple List Dictionary in Python
PPTX
Python data type
PPTX
Chapter 17 Tuples
PPTX
Chapter 15 Lists
PPTX
Regular Expressions
PDF
List , tuples, dictionaries and regular expressions in python
PPT
9781439035665 ppt ch09
PDF
Python strings
PPTX
Standard data-types-in-py
PPTX
Python Datatypes by SujithKumar
KEY
Programming with Python - Week 3
PDF
Strings Arrays
Python Collections
Python data type
Data types in python
Python dictionary
Data types in python lecture (2)
An Introduction to Tuple List Dictionary in Python
Python data type
Chapter 17 Tuples
Chapter 15 Lists
Regular Expressions
List , tuples, dictionaries and regular expressions in python
9781439035665 ppt ch09
Python strings
Standard data-types-in-py
Python Datatypes by SujithKumar
Programming with Python - Week 3
Ad

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

PPTX
11 Introduction to lists.pptx
PPTX
Chapter - 2.pptx
PPTX
Python Dynamic Data type List & Dictionaries
PPTX
dataStructuresInPython.pptx
PPTX
Chapter 3-Data structure in python programming.pptx
PDF
List in Python Using Back Developers in Using More Use.
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
beginners_python_cheat_sheet_pcc_all_bw.pdf
PPTX
python ..... _
PPTX
PPT data science python sequence numpy.pptx
PDF
Python Unit 5 Questions n Notes.pdf
PPTX
Python - List, Dictionaries, Tuples,Sets
PDF
python cheat sheat, Data science, Machine learning
PDF
2. Python Cheat Sheet.pdf
PDF
Beginner's Python Cheat Sheet
PDF
beginners_python_cheat_sheet_pcc_all (1).pdf
PPTX
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPTX
ADST university of Sussex foundation class
PDF
beginners_python_cheat_sheet -python cheat sheet description
11 Introduction to lists.pptx
Chapter - 2.pptx
Python Dynamic Data type List & Dictionaries
dataStructuresInPython.pptx
Chapter 3-Data structure in python programming.pptx
List in Python Using Back Developers in Using More Use.
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
beginners_python_cheat_sheet_pcc_all_bw.pdf
python ..... _
PPT data science python sequence numpy.pptx
Python Unit 5 Questions n Notes.pdf
Python - List, Dictionaries, Tuples,Sets
python cheat sheat, Data science, Machine learning
2. Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet
beginners_python_cheat_sheet_pcc_all (1).pdf
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
ADST university of Sussex foundation class
beginners_python_cheat_sheet -python cheat sheet description
Ad

More from Anton Kasyanov (7)

PDF
spaCy lightning talk for KyivPy #21
PDF
Introduction to Computer Vision (uapycon 2017)
PDF
aiohttp intro
PDF
Anton Kasyanov, Introduction to Python, Lecture5
PDF
Anton Kasyanov, Introduction to Python, Lecture3
PDF
Anton Kasyanov, Introduction to Python, Lecture2
PDF
Anton Kasyanov, Introduction to Python, Lecture1
spaCy lightning talk for KyivPy #21
Introduction to Computer Vision (uapycon 2017)
aiohttp intro
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture2
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