Python 67557: Cs - Huji Fall 2014
Python 67557: Cs - Huji Fall 2014
67557
Lecture 2
CS.HUJI
Fall 2014 - "
Dr. Arie Schlesinger
Containers of data
Motivation: keep data and processing
tools close by,
11/8/2014 10:37:29 PM
Some classifications
Simple objects, :
int, float, bool (non iterable)
Containers of objects : (iterable)
str, list, tuple, range, set, frozenset, dict
11/8/2014 10:37:29 PM
Order
Sequences: ordered Containers
A sequence is a container whose elements are ordered
and can be accessed by their position index, starting
from 0. Example, the 1st element in the string:
>>> s=abc
>>> s[0]
a
Containers: strings, lists, tuples, range,..
Freedom
Mutable: list,
set, dictionary
frozenset, range
11/8/2014 10:37:29 PM
: set, dictionary
float, bool
11/8/2014 10:37:29 PM
sequences
strings, lists, tuples, range
11/8/2014 10:37:29 PM
Sequences
Tuples
Contain 0 or more items of mixed types, including other
containers Immutable
Strings
Contain a seq of 0 or more single chars Immutable
Lists
Contain a seq of 0 or more items of mixed types, including
other containers Mutable
Ranges
Contain
a seq of 0 or more ordered integers ! - immutable
11/8/2014 10:37:29 PM
Similar Syntax
The three sequences types : tuples, strings, and
lists, have similar syntax and functionality
11/8/2014 10:37:29 PM
10
Sequences
Tuples : defined using parentheses, and commas.
>>> tup = (12, 'bcd', 3.45, (1,2), 'efg')
Lists : defined using square brackets, and commas.
>>> liz = ["bcd", 23, 3.23, 12]
Strings are defined using quotes (", ', or """).
>>> st = "abc"
>>> st = 'abc'
>>> st = """an example
of a multi-line string that uses triple quotes."""
Empty seq: [], (), ''
11/8/2014 10:37:29 PM
11
Sequence indexing
11/8/2014 10:37:29 PM
12
Indexing
You can access individual elements of a tuple, list, or string
using square bracket indexing notation, ( 0 based)
>>> tup = (12, bcd, 3.45, (1,2), efg)
>>> tup[1] # 2nd element in the tuple.
bcd
>>> liz = [bcd, 23, 3.23, 12]
>>> liz[1] # 2nd element in the list.
23
>>> st = bcd
>>> st[1] # 2nd char in string.
c
The index is an expression that evaluates to
an
int
11/8/2014
10:37:29 PM
13
14
Sequence slicing
11/8/2014 10:37:29 PM
15
Slicing
>>> tup = (12, bcd, 3.45, (1,2), efg)
>>> t[1:4]
(bcd, 3.45, (1,2))
Return a same-class-container, with a subset of the
original members.
It starts copying from the first index, and stops
copying before the second index.
negative indices can be used :
>>> t[1:-1]
(bcd, 3.45, (1,2))
11/8/2014 10:37:29 PM
16
Slicing defaults
>>> tup = (12, bcd, 3.45, (1,2), efg)
Without a first index, it starts from position 0:
>>> t[:2]
(12, bcd)
Without the second index, it starts at the first index
until end of the container.
>>> t[2:]
(3.45, (1,2), efg)
11/8/2014 10:37:29 PM
17
18
11/8/2014 10:37:29 PM
19
20
The in Operator
membership test, returns True or False :
>>> t
>>> 3
False
>>> 4
True
>>> 4
False
= [1, 2, 4, 5]
in t
in t
not in t
11/8/2014 10:37:29 PM
21
22
The + Operator
The + operator produces a new tuple, list, or
string whose value is the concatenation of its
arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> The + + Beatles
The Beatles
11/8/2014 10:37:29 PM
23
The * Operator
The * operator produces a new tuple, list, or
string that repeats the original content.
>>>
(1,
>>>
[1,
(1, 2, 3) *
2, 3, 1, 2,
[1, 2, 3] *
2, 3, 1, 2,
3
3, 1, 2, 3)
3
3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Its operands are a seq, and an int
11/8/2014 10:37:29 PM
24
Mutability:
Tuples vs. Lists
11/8/2014 10:37:29 PM
25
Tuples: Immutable
>>> tup = (12, bcd, 3.45, (1,2), efg)
>>> tup[2] = 2
TypeError: object doesn't support item assignment
Lists: Mutable
Lists are mutable: it is possible to change their
content (strings are immutable)
Assign to a legal position:
>>> liz = [abc, 12, 4.34, 23]
>>> liz[1] = 35 # assignment
>>> liz
[abc, 35, 4.34, 23]
11/8/2014 10:37:29 PM
27
More examples
>>> myList
[1, 'a', -2.7]
>>> myList[0]='Iosi'
>>> myList
['Iosi', 'a', -2.7]
28
Assignment to slices1
Assignment to slices can even change the size of
the list or clear it entirely:
>>> letters =['a,'b,'c,'d,'e,'f,'g']
# replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
11/8/2014 10:37:29 PM
29
Assignment to slices2
# now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
30
11/8/2014 10:37:29 PM
31
nesting lists
Create lists containing other lists:
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c'] # list a
>>> x[0][1]
'b'
11/8/2014 10:37:29 PM
32
33
11/8/2014 10:37:29 PM
34
Append
>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> x
11/8/2014 10:37:29 PM
35
Extend
>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> x
[1, 2, 3, 4, 5]
11/8/2014 10:37:29 PM
36
37
li = [5, 2, 6, 8]
li.reverse() # reverse the list in place
li
6, 2, 5]
11/8/2014 10:37:29 PM
38
39
More on list(),tuple()
list(iterable), tuple(iterable) are constructors that
decompose their arg and create a list/tuple from its
elements:
>>> list('abc')
['a', 'b', 'c']
>>> list([1,2])
[1, 2]
>>> list((11,22))
[11, 22]
>>> list(12)
TypeError: 'int' object is not iterable
(other types have similar constructors: set(), dict()
which decompose some iterable and use its elems)
>>> b=1,2
# a tuple without
parens
>>> a
(1, 2)
>>> b
(1, 2)
42
43
Swap
>>> x,y=y,x
>>> x
22
>>> y
11
>>> x,y
(22,11)
44
Swap de luxe
Assume:
>>> a=1; b=2
>>> a
1
>>> b
2
# swap de lux made by unpacking
>>> a,b=b,a+b
>>> a
2
>>> b
3
45
11/8/2014 10:37:29 PM
47
range,xrange
The built-in function range([i,]j [,step])
creates an object that represents a range of integers
k such that i <= k < j.
i, step are optional, and have default values of 0
and 1, respectively.
range(10), range(0,10),range(3,21,4)
An xrange() object calculates its values only when accessed, in a for loop
or with a list(), tuple() constructor
48
49
Les Iterables
Iterable: An object(container)
capable of returning its
members one at a time.
11/8/2014 10:37:29 PM
50
Who is iterable?
all sequence types (like list, str, tuple, range)
11/8/2014 10:37:29 PM
51
Iterators
An iterator represents a stream of data
52
Iterator examples
>>>
>>>
>>>
'a'
>>>
'b'
>>>
'c
s='abc'
# s is iterable
its=iter(s) # iter(s) creates an iterator to s
its.next()
# next(its) returns the next item in s
its.next()
its.next()
ErrorStopIteration
To do it again repeat(refill) its=iter()
11/8/2014 10:37:29 PM
53
xrange show
>>> xrange(1,8,3)
xrange(1, 8, 3)
>>> list(xrange(1,8,3))
[1, 4, 7]
>>> k=iter(xrange(1,8,3))
>>> k.next()
1
>>> k.next()
4
>>> k.next()
7
>>> k.next()
StopIteration
11/8/2014 10:37:29 PM
54
About assignments
Magic integers )) : -5256 (..singletons)
>>> x=256
>>> y=256
>>> print id(x),id(y)
28190492
28190492
No for floats
>>> x=256.0
>>> y=256.0
>>> print id(x),id(y)
36792004 36791924
Reference, alias
When a program makes an assignment such
as a = b, a new reference to b is created.
>>> b = 257
>>> a = b
>>> print id(a), id(b)
28387672 28387672
>>> a is b # are the ids equal ?
True
>>> a==b # are the values equal ?
True
alias
>>> a is b
False
>>> a==b
False
>>> print a, b
258 257
>>> a = [1,2,3,4]
>>> b = a
>>> b is a
True
>>> a == b
True
# b is a reference to a
# Append element to b.
>>> a
# Notice that a is unchanged
[1, 2, [3, 4]]
>>> b[2][0] = -100 # Modify an element inside b
>>> b
[1, 2, [-100, 4], 100]
>>> a # Notice the change inside a
[1, 2, [-100, 4]]
How it works
In this case, a and b are separate list objects, but
copy.deepcopy()
The copy.deepcopy() function in copy module does
it, example:
>>>
>>>
>>>
>>>
>>>
import copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
print a is b, a==b # False, True
b[2][0] = -100
>>> b
[1, 2, [-100, 4]]
>>> a
[1, 2, [3, 4]]
# a is not changed
First-Class Objects
All objects in Python are first class,
meaning that:
items = { 'number' : 42
'text' : "Hello World"
}
Lets add some special items to this dictionary.
items["append"](Ety)
>>> nums
[1, 2, 3, 4, Ety]
Writing very compact code is possible because
everything in Python is first-class.
Cont.
>>> line = "Iosi, 1, 3.14, Malka"
>>> field_types = [str, int, float, str]
>>> raw_fields = line.split(',')
>>> fields = [ty(val) for ty,val in
zip(field_types,raw_fields)]
>>> fields
['Iosi', 1, 3.14, 'Malka']
>>> Iosi=len
>>> Iosi('abc')
3
>>> Ety = type
>>> Ety(2)
<type 'int'>
(Just dont forget the new names)
11/8/2014 10:37:29 PM
79
# function declaration
>>> mySquare(7)
49
# function call
11/8/2014 10:37:29 PM
# function call
80
82
else example
while value < limit:
if value == x:
print "Found it!"
break
value+=y
else: # see the else indentation
print x its not there ! "
11/8/2014 10:37:29 PM
83