CS2304: Sequences and Collections - Virginia...
Transcript of CS2304: Sequences and Collections - Virginia...
CS2304: Python for Java Programmers
Monti 2014
CS2304: Sequences and Collections
CS2304: Python for Java Programmers
Monti 2014
Sequences In Python
• A sequence type in python supports: • The in membership operator. • The len() function. • Slicing like we saw with strings, s[1:3]. • And is iterable (for item in mylist:).
• Python has 5 built-in sequence types. • In this set of slides we’ll talk about:
• The str, tuple, and list sequences/collections. • There are also bytearray and bytes sequence
types. • We may discuss these later in the semester.
CS2304: Python for Java Programmers
Monti 2014
First Some Review: Strings
• A collection of characters ex. “Hello World”. • Single and double quotes are pretty much
interchangeable: • So ‘Hello World’ is the same as “Hello World”. • While ‘’ or “” are acceptable, they do need to “match” so ‘ ”
won’t work. • Remember “”” “”” can be used for multi-line comments.
• Strings in Python are for the most part very flexible. • “+” Will concatenate two or more strings. • “*” Can be used as well, ex. “hello”*3.
CS2304: Python for Java Programmers
Monti 2014
Review: String Basics
• Strings can use bracket notation like arrays/strings in other languages.
• Oddly, at least coming from another language, you can also use negative indices.
• You start at the end of the string and count backwards:
>>> s = “Hello World” >>> s[0] ‘H’ >>> s[3] ‘l’
>>> s[-1] ‘d’
CS2304: Python for Java Programmers
Monti 2014
Review: String Slicing
• String “slicing” is supported, giving you substrings:
• Strings are immutable, so trying to modify an individual cell will cause an error:
• You can always create another string though.
>>> s = “Hello World” >>> s[0:3] ‘Hel’ >>> s[3:6] ‘lo ’
>>> s[0] = “L” # TypeError
CS2304: Python for Java Programmers
Monti 2014
Review: Iterating Through Strings
• Recall: We can use a for loop to move through a string.
• The loop will iterate through the characters, printing them one by one:
H e l …
for x in s: print(x)
CS2304: Python for Java Programmers
Monti 2014
Our Next Sequence: Tuples
• You can think of a tuple as being kind of a like a C struct. • Or like a Java class with only data items and without
member functions.
• You can group several different types together into a collection. • So, you can have a tuple with a string, a number, and a
boolean value. Or tuple made up of lists and other tuples.
• Each item in the tuple is an object reference. • Tuples are built-in into Python and can be created
without formally defining a new data type. • Tuples, like strings, are also immutable.
CS2304: Python for Java Programmers
Monti 2014
Creating And Using Tuples
• To create a tuple you just list values separated by commas:
• Parentheses are often used but not required: • You can return tuples:
• You can also capture the individual values:
>>> t = “hello”, 1, True
>>> t = (“hello”, 1, True)
# at the end of a function return (“hello”, 1, True) # elsewhere t = func()
x, y, z = func()
CS2304: Python for Java Programmers
Monti 2014
Tuples: Accessing The Items
• Like strings, you can use bracket notation:
• Negative indexes work too, you count from the
back or end of the tuple:
>>> t = (“Hello”, 1, True) >>> t[0] ‘Hello’ >>> t[2] True
>>> t[-1] True
CS2304: Python for Java Programmers
Monti 2014
Tuple Slicing
• Slicing is supported, giving you sub-tuples:
• Like strings, tuples are immutable, so trying to
modify an individual item will cause an error:
• You can always create another tuple though:
>>> t = (“hello”, 1, True) >>> t[0:1] ('hello',) >>> t[1:3] (1, True)
>>> t[0] = “L” # TypeError
>>> t = t[0:1] # Works fine
CS2304: Python for Java Programmers
Monti 2014
Iterating Through Tuples
• These work just like they did with strings:
• The loop will iterate through the items, printing them one by one:
hello 1 True
for x in t: print(x)
CS2304: Python for Java Programmers
Monti 2014
Other Useful Tuple Information
• Tuples support a few useful functions: • t.count(x) - gives you the number times x
occurs in the tuple. • t.index(x) - gives you the index of the left most
occurrence of x.
>>> t = (“hello”, 1, True) >>> t.count(“hello”) 1 >>> t.index(True) 1 # because 1 counts as true >>> t = (“hello”, 0, True) >>> t.index(True) 2
CS2304: Python for Java Programmers
Monti 2014
More (Hopefully) Useful Information
• You can use the + operator with tuples as well:
• Of course, this is actually creating another tuple. • The membership operator works with tuples:
>>> t = (“hello”, 1, True) >>> f = t[0:1] + (“balloons”,) + t[1:3] >>> f ('hello', 'balloons', 0, True)
>>> if “hello” in t: ... print(“We found it.”) We found it. >>> if “world” in t: ... print(“We found it.”) >>>
CS2304: Python for Java Programmers
Monti 2014
Passing Tuples To Functions
• There are a few ways to pass tuples to functions, one is fairly straightforward:
>>> t = (“hello”, 1, True) >>> func(t) # elsewhere def func(var):
# break apart the tuple here msg = var[0]+ str(var[1]) # use the pieces of the tuple
CS2304: Python for Java Programmers
Monti 2014
Passing Tuples To Functions
• You can also expand the tuple automatically using the *:
• Trying this with the tuple f(which has 4 items) will result in an error.
# note this function has 3 parameters def func2(x, y, z):
# do something x, y, and z pass
# call the function using the tuple # remember the tuple has 3 elements >>> func2(*t)
CS2304: Python for Java Programmers
Monti 2014
Now We Move On To… Lists
• A list is an ordered sequence of zero or more object references.
• Very flexible, if performance isn’t crucial lists will often take the place of what we traditionally think of as an arrays job. • There is an array type we will examine later.
• Since each item is an object reference, elements don’t have to be the same type.
• Lists, like tuples, are built-in into Python and can be created very easily.
• Lists are mutable, unlike like strings and tuples.
CS2304: Python for Java Programmers
Monti 2014
Basic List Usage
• We’ve seen this in class before, but this creates an empty list:
• We’ve also seen examples like this in projects:
• You can have different data types in the same list as well as nested lists:
>>> l = []
>>> l = [“hello”, 1, True, [.10, .15, .25]]
>>> rates = [.10, .15, .25]
CS2304: Python for Java Programmers
Monti 2014
List Slicing
• Slicing is supported, giving you sub-lists:
• Lists are mutable, so trying to modify an individual cell works as you would expect:
>>> l = [“hello”, 1, True, [.10, .15, .25]] >>> l[0:3] ['hello', 1, True] >>> l[2:4] [True, [0.1, 0.15, 0.25]]
>>> l[0] = “L” # Works fine >>> l[2] = “W” # Also works fine >>> l ['L', 1, 'W', [0.1, 0.15, 0.25]]
CS2304: Python for Java Programmers
Monti 2014
Iterating Through Lists
• Recall: We can use a for loop to move through a list.
• The loop will iterate through the items, printing them one by one:
L 1 W …
for x in l: print(x)
CS2304: Python for Java Programmers
Monti 2014
List Functions
• Like tuples, lists support count and index: • l.count(x) - gives you the number times x
occurs in the list. • l.index(x) - gives you the index of the left most
occurrence of x.
>>> l = [“hello”, 1, True] >>> l.count(“hello”) 1 >>> l.index(True) 1 # because 1 counts as true >>> l = [“hello”, 0, True] >>> l.index(True) 2
CS2304: Python for Java Programmers
Monti 2014
More List Functions
• Lists support far more functions than just count and index.
• l.append(x) - appends item x at the end of l. • l.insert(i, x) - inserts item x at index i. • l.pop() - removes the right most value in l. • l.remove(x) - removes the left most occurrence
of x. • l.reverse() - reverses the order of l in-place.
• Take a look at the book or resources online for more functions.
CS2304: Python for Java Programmers
Monti 2014
More (Hopefully) Useful Information
• You can use the + operator with lists as well:
• The membership operator works with lists:
>>> l = [] >>> l += [1, “hello”] >>> l += [[1, 2, 3]] >>> l [1, 'hello', [1, 2, 3]]
>>> if “hello” in l: ... print(“We found it.”) We found it. >>> if “world” in l: ... print(“We found it.”) >>>
CS2304: Python for Java Programmers
Monti 2014
List Comprehensions
• Let’s say you’d like to quickly create a list filed with data, you could do something like this:
• This accomplishes the same thing:
l = [] for x in range(10):
l.append(x**2) >>> l [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
l =[x**2 for x in range(10)]
CS2304: Python for Java Programmers
Monti 2014
More List Comprehensions • You can do far more interesting things with list
comprehensions: • This (more complex code) accomplishes the
same thing: l = [] for x in [1, 2, 3]:
for y in [3, 1, 4]: if x != y: l.append((x,y))
>>> l [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
CS2304: Python for Java Programmers
Monti 2014
Other Uses For List Comprehensions
• As filters:
• They also work with functions, and types other than numbers:
l = [-1, -2, 0, 2, 4] pos = [x for x in l if x >=0] >>> pos [0, 2, 4]
>>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']
CS2304: Python for Java Programmers
Monti 2014
One More Collection: Dictionaries
• The types we’ve looked at are groupings of values that you could access via l[0] or t[0]. • Regardless of type, an index (a number) is a common way to
access the collections we’ve seen so far.
• Python also has a mapping or associative array type called a dictionary.
• Instead of being indexed by numbers, a dictionary is indexed using “keys”. • So a dictionary is made up of (unordered) key & value pairs.
• A key can be any immutable type, so strings, numbers, and tuples (if they don’t contain any mutable objects).
CS2304: Python for Java Programmers
Monti 2014
Creating And Using Dictionaries
• To create an empty dictionary you use curly brackets or braces:
• To create dictionary a with some starting values: • You can then use m kind of like an array:
• You can add new items using the same method:
>>> m = {}
>>> m[“hello”] 1
m[“foobar”] = 3
>>> m = {“hello”:1, “world”:2}
CS2304: Python for Java Programmers
Monti 2014
Dictionaries: Other Useful Functions • If you want to test whether something is the
dictionary you can use get:
• There are functions to get the keys and the
values:
# “j” is not a key in the map, get will # return None if doesn’t find the key >>> m.get(“j”) is None True >>> m.get(“hello”) is not None True
>>> list(m.keys()) >>> list(m.values())
CS2304: Python for Java Programmers
Monti 2014
Iterating Through Dictionaries
• You can use for loops to iterate through all of the key, value pairs
• If you want to delete a individual piece of the dictionary:
for k, v in m.items(): print(k, v)
hello 1 world 2 foobar 3
del m[“hello”]