Some methods of list:
list.append(x): add x to the endlist.insert(i, x): insert x at position ilist.index(x): return index of the first item whose value is xlist.pop([i]): remove item at position i. default value is 0
In [29]:
pets = ['dog', 'cat', 'pig']
print pets.index('cat')
In [30]:
pets.insert(0, 'rabbit')
print pets
In [31]:
pets.pop(1)
print pets
del statement can be used to remove an item from a list given its index
In [3]:
a = range(10)
print a
In [6]:
del a[2]
print a
In [5]:
print a[:3]
In [7]:
del a[:3]
print a
list(): convert a sequence to a list
In [76]:
print list('i can eat glass')
sorted(list, [cmp=None[, key=None[, reverse]]]): return a new sorted listlist.sort([cmp=None[, key=None[, reverse]]]): sort the current list (not creating new list)where:
In [73]:
print sorted([2, 3, 1], reverse=True)
a = [2, 3, 1]
print a.sort(reverse=True)
print a
In [74]:
print sorted([
['peter', 23],
['john', 30],
['tom', 18]
], key=lambda x: x[1])
In [38]:
squares = []
for x in range(10):
squares.append(x**2)
print squares
In [14]:
print [x**2 for x in range(10)]
In [11]:
array = []
for x in [1,2,3]:
for y in [1, 2, 3]:
if x != y:
array.append((x, y))
print array
In [12]:
print [(x, y) for x in [1,2,3] for y in [1,2,3] if x != y]
In [16]:
t = (1, 2, 3, 4, 5)
print t
In [21]:
tuple([1,2,3])
Out[21]:
In [43]:
# change the tuple raise exception
t[0] = 5
In [22]:
letters = {'a', 'b', 'c', 'a'}
print letters
In [23]:
print set(['a', 'b', 'c', 'a'])
In [23]:
s = set(['a', 'b'])
s.add('c')
print s
In [104]:
pets = { 'dog', 'cat', 'pig' }
pets.add('dog')
print pets
pets.add('fish')
print pets
In [105]:
print 'fish' in pets
print 'lion' in pets
In [106]:
pets.remove('fish')
print pets
In [24]:
letters = {x for x in 'i can eat glass'}
print letters
In [75]:
for c in set('i can eat glass'):
print c,
In [ ]:
{'a', 'b'}
In [26]:
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print tel
In [27]:
tel['vu'] = 4910
In [28]:
print tel
In [26]:
print tel['jack']
In [92]:
del tel['guido']
print tel
In [29]:
print 'sape' in tel
print 'foo' in tel
dict.keys(): return list of keysdict.values(): return list of values
In [30]:
tel = {'sape': 4139, 'jack': 4098, 'guido': 4127}
print tel.keys()
print tel.values()
dict(sequence): where a sequence of (key, value) pairs
In [31]:
print dict([('sape', 4139), ('jack', 4098), ('guido', 4127)])
zip(sequence...): zip sequences together
In [115]:
zip([1, 2, 3], 'abc', 'ABC')
Out[115]:
In [116]:
print dict(zip('abc', [1, 2, 3]))
In [83]:
for name in tel:
print name, ':', tel[name]
In [32]:
tel.values()
Out[32]:
In [81]:
for telno in tel.values():
print telno
In [34]:
def firstn(n):
i = 0
while i < n:
yield i
i += 1
In [35]:
gen = firstn(10)
In [42]:
print range(50)
print firstn(50)
In [58]:
for i in range(5):
print i,
print '\n--------------------'
for i in firstn(5):
print i,
In [62]:
for i in (x ** 2 for x in range(10)):
print i,
In [45]:
for i in xrange(10):
print i,
In [47]:
list(enumerate(['dog', 'cat', 'pig']))
Out[47]:
In [89]:
print list(enumerate(['dog', 'cat', 'pig']))
print list(enumerate(['dog', 'cat', 'pig'], start=2))
In [48]:
for value in enumerate(['dog', 'cat', 'pig']):
print value
In [91]:
for index, value in enumerate(['dog', 'cat', 'pig']):
print index, ':', value
dict.iteritems(): return an iterator through items (key, value) of a dictionarydict.iterkeys(): return an iterator through key of a dictionarydict.itervalues(): return an iterator through value of a dictionary
In [52]:
print tel
In [53]:
print list(tel.iteritems())
In [54]:
for name, telno in tel.iteritems():
print name, ':', telno
In [56]:
for key in tel.iterkeys():
print key
In [57]:
import os
In [65]:
os.listdir('.')
Out[65]:
In [59]:
[file_name for file_name in os.listdir('.') if file_name.endswith('.pyc')]
Out[59]:
In [64]:
filter(lambda file_name: file_name.endswith('.pyc'), os.listdir('.'))
Out[64]:
In [61]:
os.remove('./main.pyc')
In [63]:
[os.remove(file_name) for file_name in os.listdir('.') if file_name.endswith('.pyc')]
Out[63]:
In [ ]: