More Python
Data structures
- Mechanisms to organize complex/hierarchical data in computers
- e.g. Lists and dictionaries
- Special data structures can be created for specific purposes
Lists
- Hold a list of elements
- Elements can be of any type, and types can be mixed within lists
>>> l = [2,5,7,8,9, "hello"]
>>> for element in l:
... print l
2
5
7
8
9
hello
>>> l[2] + l[1] # Indeces count from 0
12
>>> l[2:] # list slicing
[7,8,9, "hello"]
Dictionaries
- Hold a list of elements referenced by a "key"
- Elements and keys can be of any type, but keys are often strings
>>> composers = ['Bach', 'Beethoven', 'Stravinsky', 'Cage']
>>> import random
>>> print "My favorite composer is " + composers[random.randint(0,3)]
My favorite composer is Bach
>>> d = {"name": "Andres", "surname": "Cabrera", "id": 12345}
>>> print d["name"], d["surname"], "has id:", d["id"]
Andres Cabrera has id: 12345
>>> for key in d:
... print("%s:%s"%(key, d[key]))
surname:Cabrera
name:Andres
id:12345
Strings
- Strings are "lists" of characters
- Can be defined with apostrophes, quotes or triple apostrophes/quotes for multiline strings
- They support many of the operations for lists like slicing
- But they also support many string specific functions like split() and capitalize()
>>> s = "Hello World"
>>> words = s.split()
>>> print words
['Hello', 'World']
>>> ",".join(words)
'Hello,World'
>>> s.index('W')
>>> s[s.index('W'):]
'World'
File I/O
- File input and output is simple in Python and is provided by the core language
>>> f = file("test.txt", 'w')
>>> f.write("Hello")
>>> f.write(" World")
>>> f.close() # Finish writing any pending data
>>> f = file("test.txt")
>>> f = file("test.txt", 'r')
>>> f.read() # readlines() will return a list with the lines
'Hello World'
Value or reference
- When something is assigned to a variable it can be assigned by value or reference.
- i.e. a copy can be made or the variable "points" to the original memory
- Python passes almost everything by reference
- Passing by reference reduces memory usage and copying operations, but can be dangerous
>>> a = [2,3,4,5,6,7]
>>> b = a[1]
>>> print b
3
>>> b = 10
>>> print a # passed by value i.e. "copied"
[2,3,4,5,6,7]
>>> b = a
>>> b[1] = 10
>>> print a # passed by reference
[2,10,4,5,6,7]
>>> b is a
True
More Python
By mantaraya36
More Python
- 1,114