del(a[0]) # deletes element 0 del(a[2:5]) # deletes elements 2-4
>>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5]
>>> sorted([5, 2, 3, 1, 4], reverse=True) [5, 4, 3, 2, 1]
names.sorted(key = str.lower)
>>> student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=lambda student: student.age) # sort by ageNote that in examples 2 and 3 we cannot simply write
key = student[2] key = student.agebecause key is supposed to be a pointer to a function, not a value
>>> sorted(student_objects, key=lambda student: (student.age, student.name))
>>> import operator >>> sorted(student_tuples, key=itemgetter(2)) >>> sorted(student_tuples, key=itemgetter(2, 1)) # sorts first on item 2, then item 1
>>> import operator >>> sorted(student_objects, key=attrgetter('age')) # sort by grade and then by age >>> sorted(student_objects, key=attrgetter('grade', 'age'))
# \ is a line continuation character >>> people = [('brad', 50000), ('yifan', 80000), ('smiley', 15000), ('george', 20000), \ ... ('james', 10000)] >>> filter(lambda person: person[1] < 40000, people) [('smiley', 15000), ('george', 20000)]
>>> map(lambda x: x*x*x, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> vector1 = [10, 20, 30, 40, 50] >>> vector2 = [5, 10, 15, 20, 25] >>> map(lambda x,y: x+y, vector1, vector2) [15, 30, 45, 60, 75]
reduce(function, sequence, startingValue)If a starting value is not provided, then the first two values in the sequence are passed to the function on the first function call.
>>> vector1 = [10, 20, 30, 40, 50] >>> reduce(lambda x,y: x+y, vector1) 150
>>> vector1 = [10, 20, 30, 40, 50] >>> reduce(lambda x,y: x if x < y else y, vector1) # only works since 2.6 or >>> def min(x,y): ... if (x < y): ... return x ... else: ... return y ... >>> reduce(min, vector1)
from collections import deque
t = (3, 6, 9) # comma separated list in parentheses t = 3, 6, 9 # comma separated list t = 4, # singleton--must have comma at the end t = (4) # wrong--t is the integer 4 because Python # thinks 4 is an arithmetic expression in ()s
>>> t[1] 6
x, y, z = t # x = 3, y = 6, z = 9 def minmax(x, y): if x < y: return (x,y) else: return (y,x) min, max = minmax(8, 6)
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['jack'] 4098 >>> tel['guido'] = 4127
>>> 'guido' in tel True
del tel['sape']
>>> tel.keys() ['guido', 'jack']
>>> tel.values() [4127, 4098]
>>> tel.items() [('jack', 4098), ('guido', 4127)]
x = { 3, 6, 9 }
x = set([3, 6, 9]) x = set()
>>> x = { 3, 6, 9, 6, 9 } >>> x set([9, 3, 6])
>>> 3 in x True >>> 4 in x False