Python code examples:
1. find the position of an item in a list in python
the index() method
list = [“red”,”green”,”blue”]
assert list.index(“red”) == 0
2. test if a value is contain within a list
in method
list = [“red”,”green”,”purple”]
assert “red” in list
assert not “red” in list
3. insert an item into a list
insert(),add the index and value
list = [“red”,”green”]
list.insert(1,”blue)
assert list == [“red”,”blue”,”green”]
4. append an item to a list
list = [“green”,”red”]
list.append(“blue”)
assert list == [“green”,”red”,”blue”]
5. find the last element a list
python supports negative indices
colors = [“red”,”green”,”blue”]
assert colors[-1] == “blue”
6. get the current time and date
import datetime
now = datetime.datetime.now()
print “Year:%d” % now.year
print now.strftime(“%Y/%m/%d”)
7. get the name of a weekday
import datetime
d = datetime.date(2010,12,24)
assert d.strftime(“%a”) == “Fri”
assert d.strftime(“%A”) == “Friday”
8. create an iterator
class OddIterator(object):
def __init__(self):
self.value = -1
def __iter__(self):
return self
def next(self):
self.value +=2
return self.value
iter = OddIterator()
assert iter.next() ==1
test for for-in syntax:
iter = OddIterator()
for i in iter:
print i
if i >= 9:
break
9. create an iterating counter
itertools module provides a count generator
import itertools
counter = itertools.count(10)
counter = itertools.count(10,2)
10. append two lists
c1 = [“red”,”green”,”blue”]
c2 = [“Orange”,”apple”]
c1.extend(c2)
c3 = c1+c2
list can also be appended using the + operator
11. convert a tuple to a list
color_tuple = (“red”,”green”)
color_list = list(color_tuple)
assert color_list == [“red”,”green”]
12. iterate through a list using an index
colors = [“red”,”green”,”blue”]
for color in colors:
print color
enumerate() function
colors = [“red”,”green”,”blue”]
for i,color in enumerate(colors):
print i, color
13. delete items from a dictionary
use the del statement to delete individual items for a dicitionary or clear()
d = {}
d[“name”] = “Fido”
assert d.has_key(“name”)
#del the item
del d[“name”]
assert not d.has_key(“name”)
# add a couple of items
d[“name”] = “Fido”
d[“type” ]=”dot”
assert len(d) == 2
d.clear()
assert lend(d) == 0
14. access the docstring of a class
class Foo:
pass
class Bar:
“”” Representation of a BAr “””
Assert Foo._doc_ == None
Assert Bar._doc_==”Representation of a Bar”