Idiomatic Python: the very basic stuff
Check for something
1 2 | if 'h' in 'hello' : print 'y' if something in someset: go() |
Building strings in linear time
1 2 | truth = ' '.join((' why ', ' so ', ' serious')) # 'whysoserious' |
String Formatting
1 | print '{0} so {1}?' . format ( 'Why' , 'serious' ) |
Enumerate
1 2 3 4 5 6 7 8 9 | >>> for c in enumerate ( 'no' ): ... print c ( 0 , 'n' ) ( 1 , 'o' ) >>> for pos, value in enumerate ([ 'one' , 'more' , 'time' ]): ... if pos < 1 or pos > = 2 : print value one time |
List comprehension
1 2 3 4 5 6 7 | a = [ 1 , 2 , 3 , 4 ] b = [x for x in a] [i * 3 for i in data if i > 10 ] # flattening a list: [ x for y in l for x in y ] |
Zip
1 | d = dict ( zip (keys, values)) |
Using the context manager
This is bad: if an exception occurs, the file handle is never closed.
1 2 3 4 5 | f = open (path_to_file, 'r' ) for line in f.readlines(): if some_function_that_throws_exceptions(line): # do something f.close() |
Use with instead:
1 2 3 4 5 | with open (path_to_file, 'r' ) as f: for line in f: if some_function_that_throws_exceptions(line): # do something # No need to explicitly call 'close' |