This short python tutorial list some of the useful techniques that python programmers can use to store (contain) and access data.. It's by no means all you need, but perhaps it will give you a start. (NOTE: All of the code listed has been copy/pasted from an interactive Python session. This allows you to see how I used python to test things. However, if you want to copy/paste this code and use it, you need to leave out the >>>.)
A lot of this info (and more) can be found in the Python Tutorial.
Menu: strings | tuples | lists | dictionaries | functions |
A lot of info can be stored in strings, and python contains a LOT of string processing functions. Below are some code fragments that let you do various things with strings.
Assign a string to a variable, then print the contents of that string.:
>>> name = "Brad" >>> print name Brad >>> print "Hi, my name is ", name,"." Hi, my name is Brad .
Print the lenght of a string (Note that name still points to the value "Brad")
>>> print len(name) 4
Access one letter of a string. (Notice that this works like simple arrays in other languages! Remember, indexes start at 0)
>>> print name[1] r
Slicing a string. Here, we'll take a slice of the 2nd - 4th elements of name (thats index 1 to 4). You can slice strings using syntax like this "string[beginning:end]"
>>> print name[1:4] rad
Slice from beginning to the 2nd element
>>> print name[:2] Br
Slice from the 2nd element to the end
>>> print name[2:] ad
Slice from beginning to end (Note that this is the same as printing the whole string)
>>> print name[:] Brad
Menu: strings | tuples | lists | dictionaries | functions |
Tuples are collections of items, again similar to arrays. However, tuples can contain any type of data. Tuples are also immutable
Create a Tuple: (notice that we use parentheses ( ) to surroud our items)
>>> pets = ("dogs", "cats", "birds", "fish")
>>> print pets
('dogs', 'cats', 'birds', 'fish')
Print one element of a tuple:
>>> print pets[2] birds
Check for membership in a tuple (using the in operator)
>>> if "cats" in pets: ... print "we have cats!" ... we have cats!
Iterate through a tuple:
>>> for item in pets: ... print item, "are pets" ... dogs are pets cats are pets birds are pets fish are pets
Slicing tuples (works just like slicing strings)
>>> pets[1:3]
('cats', 'birds')
Immutability: We can't change the value of an element in a tuple:
>>> pets[0] = "bugs" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
Concatenating Tuples. We can append to tuples together to form a new tuple:
>>> livestock = ("cows", "sheep") # This creates a new tuple
>>> print livestock
('cows', 'sheep')
>>> animals = pets + livestock # concatenate with the + operator
>>> print animals
('dogs', 'cats', 'birds', 'fish', 'cows', 'sheep')
Find the length of a tuple (or how many elments it contains)
>>> len(animals) 6 >>> len(pets) 4 >>> len(livestock) 2
Create a tuple containing different data types:
>>> t = ('this', "tuple contains many data types", 5)
>>> print t
('this', 'tuple contains many data types', 5)
Menu: strings | tuples | lists | dictionaries | functions |
Lists are very similar to tuples, however they are mutable. Like tuples, lists can contain a collection of various data types.
Create a list, then print it's elements a couple different ways. (Notice we use square brackets [ ] to surround our items!)
>>> courses = [1900, 2150, "Discrete Math", 2701] >>> print courses [1900, 2150, 'Discrete Math', 2701] >>> for c in courses: ... print c ... 1900 2150 Discrete Math 2701
Access one element of a list:
>>> print courses[2] Discrete Math >>> print courses[1] 2150 >>> print courses[3] 2701
Slice a list (again, works just like slicing strings)
>>> print courses[0:2] [1900, 2150] >>> print courses[1:] [2150, 'Discrete Math', 2701]
Find the length of a list:
>>> print len(courses) 4
Mutability - we can change individual elements of a list:
>>> print courses [1900, 2150, 'Discrete Math', 2701] >>> courses[1] = 1800 >>> print courses [1900, 1800, 'Discrete Math', 2701]
Delete an element from a list (using the del command):
>>> print courses [1900, 1800, 'Discrete Math', 2701] >>> del courses[2] >>> print courses [1900, 1800, 2701]
We can also delete slices:
>>> courses = [1900, 2150, "Discrete Math", 2701] >>> del courses[1:3] >>> print courses [1900, 2701]
List Methods: Lists also have some built-in methods that let us do various things!
For more info on these, check out this link More on Lists in Python documentation.
append() will add an item to the end of the list:
>>> print courses
[1900, 2701]
>>> courses.append("Calculus")
>>> print courses
[1900, 2701, 'Calculus']
insert(i, value) - insterts "value" at position "i"
>>> print courses [1900, 2701, 'Calculus'] >>> courses.insert(0, "English") >>> print courses ['English', 1900, 2701, 'Calculus'] >>> courses.insert(1, 1800) >>> print courses ['English', 1800, 1900, 2701, 'Calculus']
sort() will let us sort a list
>>> courses.sort() >>> print courses [1800, 1900, 2701, 'Calculus', 'English']
reverse() will sort in reverse order:
>>> courses.reverse() >>> print courses ['English', 'Calculus', 2701, 1900, 1800]
count(value) - count the number of times "value" appears in a list:
>>> names = ["Brad", "Bob", "Bill", "Brandon", "Brad", "Brad"]
>>> names.count("Brad")
3
>>> names.count("Bill")
1
index(value) - return the position of the first occurance of "value" in the list
>>> names = ["Brad", "Bob", "Bill", "Brandon", "Brad", "Brad"]
>>> names.index("Brad")
0
>>> names.index("Bill")
2
Lists can also contain other containers, such as tuples!
>>> phoneNumbers = [("Brad", "901-678-2986"), ("Whoever", "555-555-1234")]
>>> print phoneNumbers[0]
('Brad', '901-678-2986')
>>> print phoneNumbers[0][0]
Brad
>>> print phoneNumbers[0][1]
901-678-2986
Unpacking Sequences (lists, tuples, etc) - If you know that a list contains tuples with 2 elements, you can "unpack" them by storing each element in its own variable:
>>> phoneNumbers = [("Brad", "901-678-2986"), ("Whoever", "555-555-1234")]
>>> name, number = phoneNumbers[1]
>>> print name
Whoever
>>> print number
555-555-1234
Menu: strings | tuples | lists | dictionaries | functions |
Dictionaries are like Associative Arrays, or Hashes in other languages. A dictionary consists of a key and a value. Keys MUST be unique, and they are used to retrieve the associated value. This works much like the way we look up a definition for a word in a real dictionary!
Creating a Dictionary: variable = { "key1":"value1", "key2":"value2", ... "keyN":"valueN"} (Notice that the order of items in our dictionary does not matter!))
>>> addressBook = {"Brad":"123 Some Pl.", "Bob":"456 Some St."}
>>> print addressBook
{'Bob': '456 Some St.', 'Brad': '123 Some Pl.'}
Performing a Lookup: (e.g., what is Brad's address?)
>>> addressBook["Brad"] '123 Some Pl.'
Adding a definition:
>>> addressBook["Bill"] = "456 Some Ln."
>>> print addressBook
{'Bob': '456 Some St.', 'Bill': '456 Some Ln.', 'Brad': '123 Some Pl.'}
Making Changes:
>>> addressBook["Brad"] '123 Some Pl.' >>> addressBook["Brad"] = "789 Somewhere Else Ave." >>> addressBook["Brad"] '789 Somewhere Else Ave.'
Delete from a Dictionary
>>> del addressBook["Brad"]
>>> print addressBook
{'Bob': '456 Some St.', 'Bill': '456 Some Ln.'}
Dictionary Methods: Dictionaries also have some built-in methods that allow you to do variouse things.
keys() - Get a list of Keys in a Dictionary:
>>> addressBook.keys() ['Bob', 'Bill']
values() - Get a list of Values in a Dictionary:
>>> addressBook.values() ['456 Some St.', '456 Some Ln.']
items() - Get a list of items (Notice that this is a List whose elments are 2-element Tuples!)
>>> addressBook.items()
[('Bob', '456 Some St.'), ('Bill', '456 Some Ln.')]
get(key, [default]) - Try to get the value for a key, but if the key does not exist, return the optional default.
>>> addressBook.get("Brad", "No Brad Here!")
'No Brad Here!'
In python, a function is defined with the def keyword. Here are some simple examples:
Define and call a simple function:
>>> def sayHi(): ... """A funtion that just prints the word Hi""" ... print "Hi" ... >>> sayHi() Hi
A function that returns a value:
>>> def returnFive(): ... """ A function that returns the value 5 """ ... return 5 ... >>> print returnFive() 5 >>> returnFive() 5
A function with an argument:
>>> def sayWord(word):
... """ A function that prints the given word """
... print word
...
>>> sayWord("woot")
woot
>>> sayWord("blah")
blah
>>> sayWord(7)
7
>>> t = (1, 2, 3)
>>> sayWord(t)
(1, 2, 3)
A function with 2 arguments:
>>> def mult(x, y): ... """ A function that returns the product of 2 numbers """ ... product = x * y ... return product ... >>> mult(3, 5) 15 >>> mult(100, 100) 10000 >>> >>> num1 = 15 >>> num2 = 15 >>> mult(num1, num2) 225
Menu: strings | tuples | lists | dictionaries | functions |