for i in range(10):do something
exec"do something\n"*10
i+=1;j+=1i,j=i+1,j+1raw_input(), which returns a string. It's a lot better than importing sys or any such things, and pretty short too.string[::-1]. Very handy.
raw_input more than once, it is always more efficient to alias it, r=raw_input.print"".join(L), other ways always end up being longer."ab"[x>0] gives "a" if x is 0, "b" if x is above zero.
for a, (b, c) in ((1, "ab"), (2, "ba")):
....print a, b, c
1 a b
2 b a
print'%i'%d saves one byte versus print int(d).l[x+1:x-1:-1] as substitute for x[x:x+2][::-1] when x>0.for, while and try have an optional else-clause.True: use all(seq).any(seq) to check if at least one element evaluates to True.hex(n), oct(n) and int('...', base) is very useful when you need to encode something.convert = lambda number, base: ''.join(str(number/i % base) for i in (..., base**3, base*base, b,1))''.join(...) as a replacement for loops when the loop body only contains expressions.%= is overloaded for strings: s = '%c'; s%=54; print s # prints 6int('...') works on strings of zero-padded numerals: int('009') gives 9. Useful in conjunction with string interleaving and slicing.'#'.join('abc') gives 'a#b#c'.'%s' converts any type or object with str(), '%r' converts with repr().range(1e3) is shorter than range(1000). This gives a warning, but stderr is ignored in codegolf.
`x`can be used instead ofstr(x), if x is int (not long, because it follows with 'L')use of bounded methods and aliases can shave some bytes, e.g.
j=''.join; R=rangeget rid of parentheses with bitwise operators. bitwise operators have lower precedences than arithmetic ones, so one can write
3+x>>2instead of(3+x)/4-~xand~-xare equivalent tox+1andx-1, but without (possible) parentheses.zip(x, x[1:])generates[(x[0], x[1]), (x[1], x[2]), ..., (x[-2], x[-1])], good for lookahead and/or lookbehind.conditional expressions are extremely common. if you can avoid side effects,
(x,y)[cond]will be a basic choice. if x=1 and cond>=0 theny**condcan be used. if both x and y are fixed strings with similar length and cond is 0 or 1 then(x[0]+y[0]+x[1]+y[1]+...)[cond::2]can be used. and so on...bool can be treated as int, and vice versa (although some tips don't work for integer rather than 0 or 1)
some comparisons can be chained. e.g.
a>1<binstead ofa>1 and b>1list.append(item)can be shortened withlist += [item], orlist += item,.one can use unused variables to trigger exceptions and terminate the program. (stderr is ignored in codegolf)
as well as ruby,
0or 1is valid python code. of course0 or1is not. (note that no spaces between 0 and or)Obviously there could be more.