List¶
Snippets on list manipulation.
check if a list is empty¶
if not a:
print "List is empty"
empty a list¶
del l[:]
shuffle a list¶
from random import shuffle
# works in place
l = range(10)
shuffle(l)
append vs extend¶
append:
x = [1, 2, 3]
x.append([4, 5])
# [1, 2, 3, [4, 5]]
extend:
x = [1, 2, 3]
x.extend([4, 5])
# [1, 2, 3, 4, 5]
split a list into evenly sized chunks¶
Here’s a generator that yields the chunks you want:
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i+n]
finding the index of an item¶
>>> ["foo","bar","baz"].index('bar')
1
sort a list of dictionaries by values of the dictionary¶
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
randomly select an item from a list¶
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.choice(foo)
list comprehension¶
new_list = [i * 2 for i in [1, 2, 3]]