Title: Information Infrastructure II
1Information Infrastructure II
- I211 Week 3
- Rajarshi Guha
2Topics To Be Covered
- Lists
- Strings as lists string methods
- Tuples
- Dictionaries
- File operations
3Lists
- A list is a vector of objects
- Numbers
- Strings
- Anything!
Elements of the list
1
A
ab
2.5
-2
Element 1
Element 0
Element 5
4Creating a List
- Put values between
- represents an empty list
- Can be used to represent False (like 0)
gases 'He', 'Ne', 'Ar', 'Kr' print
gases 'He', 'Ne', 'Ar', 'Kr' alist
1.2345, "Hello World", 4567383, 'abcdefg'
print alist 1.2344999999999999, 'Hello World',
4567383, 'abcdefg'
5Creating a List
- Since a list can hold anything, it can also
contain another list! - This willl allow us to use lists as 2D matrices
l 1, 3, 'a', 'b', 'c', 10, 'hello'
print l 1, 3, 'a', 'b', 'c', 10, 'hello'
6Accessing List Elements
- a.k.a list indexing
- Since a list is a vector of objects, we can
access a list by indicating the position of the
element - We can use a number (such as 1, 2 or 10)
- We can use a variable containing the number
- Numbering starts from 0 !!!
- len( ) gives the length of the list
7Accessing List Elements
l 1, 3, 'a', 'b', 'c', 10, 'hello'
l0 1 l2 'a', 'b', 'c' x 4
lx 'hello len(l) 5
- If you go beyond the last element of the list,
you get an error
l5 Traceback (most recent call last)
File "", line 1, in ? IndexError list
index out of range
8Lists References
- Previously we learned that variables refer to an
object - Variables dont have types
- Two variables can refer to the same object
- Changing one variable doesnt change the other
- Lists are a little different
9Lists and References
What happensto L2?
10Negative Indices
- We can supply a negative index
- Indicates that we start from the end of the list
-5
-4
-3
-2
-1
alist 1, 'A', 'ab', 2.5, '' alist 1,
'A', 'ab', 2.5, '' alist-1 ''
alist-2 2.5
1
A
ab
2.5
alist
11List Slicing
- Slicing lets us access ranges from a list
- We write a slice as alist14
- Returns elements 1, 2, and 3 (not 4!!)
0
1
2
3
4
1
A
ab
2.5
alist
alist25
alist02
12List Slicing
- But going beyond the last index does not give an
error - Truncates out ofrange indices
- We can also use negative indices
0
1
2
3
4
1
A
ab
2.5
alist
alist210
alist1-2
13Slicing Shortcuts
- alistx returns all elements from 0 to x-1
- alistx returns all elements from x to the end
of the list
alist3
1
A
ab
2.5
alist
alist3
14Modifying Lists
- Assign a new value to a position in the list by
doing xi v - But i must be a valid index
a 'p', 'q', 'r', 's', 't' a3
'hello' print a 'p', 'q', 'r', 'hello',
't' a-1 1234 print a 'p', 'q', 'r',
'hello', 1234
a 'p', 'q', 'r' a5 'hi' Traceback
(most recent call last) File "", line
1, in ? IndexError list assignment index out of
range
15Modifying Lists
- We can add items to the end of the listby using
append() - But you can only addone thing at a time
a 'p', 'q', 'r' a.append(123)
print a 'p', 'q', 'r', 123
a 'p', 'q', 'r' a.append('s',
't') Traceback (most recent call last) File
"", line 1, in ? TypeError append() takes
exactly one argument (2 given)
16Modifying Lists
- So what if we want to append more than one item
to a list? - Use the extend() method
- So the items we wantto append, should be placed
in a list - The original list is then extended with the new
list
a 'p', 'q', 'r' a.extend( 's', 't'
) print a 'p', 'q', 'r', 's', 't'
17Deleting Elements
- Delete items at a specific position
- We can also delete using slices
a 'p', 'q', 'r', 's' del a2
print a 'p', 'q', 's'
a 'p', 'q', 'r', 's' del a13
print a 'p', 's'
18Useful List Methods
a b, a, c, d, d
19Testing Membership
- We just saw the find method
- A more English like way is to do
- x in y
- If the item denoted by x is present in the list
y, the expression is True, otherwise False - Checks on an elementby element basis
a 'p', 'q', 'r', 123 123 in
a True 'xyz' in a False 'p', 'q' in
a False
20Looping Over a List
- We can use the for x in y construct
- y is the list
- x will be each consecutive element
- Here we just print each element
- We can do anything withthe element
a 'p', 'q', 'r', 123 for x in a print
x p q r 123
21Looping With Lists
- So far weve seen different ways to loop
- while
- for
- How do we do the C for loop?
- for (i 0 i
- Use the range() function
22Looping With Lists
- range(0, n) returns a list with the numbers from
0 to n-1 - This can be shortened to range(n), which always
starts from 0 - We could also do range(p, q)
- What would we get?
- Since we get back a list, we can then use
thefor x in y method we just saw - We can use incrementsother than 1 by
doingrange(p, q, step)
for x in range(0,4) print x 0 1 2 3
range(3, 15, 2) 3, 5, 7, 9, 11, 13
23List Within Lists
- A list can contain anything
- So we can add lists to lists
a 1,2,3, 'a', 'b', 'c', 'd', 'ab',
2.5 print a 1, 2, 3, 'a', 'b', 'c',
'd', 'ab', 2.5 a0 1, 2, 3 a3 2.5
ab
2.5
1
2
3
a
b
c
d
24Tuples
- A tuple is a list that cant be changed
a (1, 2, 'hello') a (1, 2, 'hello')
a1 2 a0 3 Traceback (most recent call
last) File "", line 1, in ? TypeError
object doesn't support item assignment
25Multi-valued Assignment
- Ordinarily we do a x
- In Python we can do a, b x, y
- This does a x b y all in one go
- Nice for swapping a, b b, a
- Nice for looping through lists of lists
a 1,2, 3,4, 5,6 for x,y in a
print x,y ... 1 2 3 4 5 6
26Strings as Lists
- A string is a list that cant be changed
- All the indexingrules can be usedon a string
- But we cantmodify elements of the string
a 'this is a string' a0 't'
a04 'this' a-5-1 'trin'
a1 'b' Traceback (most recent call
last) File "", line 1, in ? TypeError
object doesn't support item assignment
27String Methods
- A method is a function tied to a specific object
- An object can be a string, list, etc.
- Well look at string methods
- Later on well write our own
- We call a method by object.method()
This could be a string or list or any type of
object
This is a method on that object
28What Can We Do With a String?
- Replace portions of it
- Convert to lower or upper case
- Find a smaller string within a larger one
- Clear white space at the start and end of a
string - Split a string in different ways
29Examples
a "this Is A Longer string"
a.lower() 'this is a longer string'
a.upper() 'THIS IS A LONGER STRING'
a.find("onger") 11 a.replace("Longer",
"shorter") 'this Is A shorter string'
a.split(" ") 'this', 'Is', 'A', 'Longer',
'string'
In each case we get a new string. The old
string is unchanged
30Dictionaries
- In many cases we would like to associate a name
with a value - Names and ages (John 24)
- Counts of birds (Sparrow 3)
- A list wont let us do this (easily)
- So we use a dictionary
31Dictionaries
- Dictionaries are basically collections of key,
value pairs - Keys are usually strings, butcan actually be any
object - Values can be any object
- Keys are not sorted!
Key
Value
32Using Dictionaries
- Create an empty dictionary by d
- You get values by specifying the key for the
value - Keys are unique!
- You can get all thekeys by callingd.keys()
- You can get all the values by callingd.values()
d john 24, mary 22, joe 26
djohn 24 d'mark' Traceback (most
recent call last) File "", line 1, in
? KeyError 'mark'
33Dictionaries are Unsorted
- When we create a list, the elements remain in the
order we specified - Dictionary keys are unsorted
- So the order in which we specify the elements may
not be the order in which get them - So dont depend on theordering of the keys
d a 1, b 2, c 3 d 'a' 1,
'c' 3, 'b' 2
34Looping Over a Dictionary
- Looping over a dictionary implies that we loop
over the keys - Different from lists! There, we loop over
indices, not values - Two ways
- We can get thekeys and loopover them
- Loop over the dictionary, whichautomatically
loopsover the keys
d a 1, b 2, c 3, d 4
method 1 For key in d.keys() print Key ,
key, Value , dkey method 2 For key in
d print Key , key, Value , dkey
Allows youto loop overthe keys insorted order
35Assigning Deleting
- If the key exists then the old value is
overwritten - If the key does not exist it creates a new entry
- To delete an entry, do del dk
- Wont work if the key, k, doesntexist
d a 1, b 2 d 'a' 1, 'b'
2 da 2 d a 2, b 2
dc 3 d 'a' 2, 'c' 3, 'b' 2
36Files
- Typing lists and text is very boring!
- Nicer to read it from a file
- Whats involved?
- Opening a file
- Reading from a file
- Writing to a file
- What do we get as a result?
37Using a File
- We use the built-in function open
- Takes 2 arguments
- Name of the file
- Whether to read (r) or write (w)
- We get back a file object (which has certain
methods)
38Reading from a File
f open('christmas.txt', 'r') contents
f.read() len(contents) 180929
Reads in each byte of the file
f open('christmas.txt', 'r') contents
f.readlines() len(contents) 4184
Reads in each line of the file
f open('christmas.txt', 'r') aline
f.readline() print aline CONTENTS
Reads in one line of the file
39What Are Bytes Lines?
- Stave IV The Last of the Spirits
- Stave V The End of It
- STAVE I MARLEY'S GHOST
- MARLEY was dead to begin with. There is no doubt
- whatever about that. The register of his burial
was - signed by the clergyman, the clerk, the
undertaker, - and the chief mourner. Scrooge signed it and
- Scrooge's name was good upon 'Change, for
anything he - chose to put his hand to. Old Marley was as dead
as a - door-nail.
A single byte. In general thismeans a
singlecharacter.But this is notalways the
case!
A single lineA line can be blank. A line
usually ends with a \n character. So a blank
line is usually just a \n
40Reading Single Bytes
f open('christmas.txt', 'r') contents
f.read() len(contents) 180929
- If we dont specifyan argument toread() it will
read allthe bytes in the file. - If we want the first 10 bytes, we can call
read(10) - We get back a list - each element is a single byte
41Reading All the Lines
- readlines() readsthe whole file
- Returns a list
- Each element is a line of the file
- We can print each line by looping over the list
f open('christmas.txt', 'r') contents
f.readlines() len(contents) 4184
42Reading a Single Line
f open('christmas.txt', 'r') aline
f.readline() print aline CONTENTS
- readline() reads1 line from the file
- If you call it again it reads the next line
- If there are no more lines, it will return None
(equivalent to False)
- We can read the whole file, line by line
43Reading Lines One By One
- We can read a file line by line in two ways
- Call readline() in a loop, exit when we get None
- Loop over the file !
f open('christmas.txt', 'r') line
f.readline() while line line f.readline()
if not line break print line
f open('christmas.txt', 'r') for line
in f ... print line
44Writing to a File
- Very similar to reading
- Open the file
- Write text
- Close the file
f open('afile.txt', 'w') f.write("The
first line in the file") f.write("The second
line in the file") f.close()
Does this do whatwe expect it to do?