g | x | w | all
Bytes Lang Time Link
nan230302T010102ZShadowRa
nan230210T212053ZShadowRa
nanConditionals can be lengthy. In some cases110128T001242Zmoinudin
nan250724T211844ZCursorCo
nan250721T005216ZLucenapo
nan250305T025746ZLucenapo
nan221113T121628ZRhaixer
nan241212T032025Ztsh
nan240818T003330ZLucenapo
nanAlthough python doesn't have very golfable switch statements the match/case syntax since Python 3.10140412T194400ZJustin
nan220119T163743Zquintopi
nanA common pattern is to use listmaplambda c c.func240325T180711ZTheUltim
nanMultiline Integer Inputs231008T084341ZNishant
nan231228T200732Zl4m2
nanAnother tip this is a pretty useful but rarely useable alternative ternary operator which we use in Scratch * and +. This uses the fact the booleans are equal to 0 and 1221223T130725ZRhaixer
002Check if a number is a power of171227T025926Zxnor
nan230522T164302ZHunaphu
nan230505T122713Zmousetai
nan141107T082054Zxnor
nan221104T030430ZDialFros
nan170803T143439ZDead Pos
011Instead of not in220901T171451ZnaffetS
nan220629T084804ZnTerior
nan201226T161418ZDanis
nan191125T135750ZDead Pos
nan110128T033220ZMing-Tan
nan110127T235809Zmoinudin
nan110703T211501Zzhazam
nan220519T074516Zjezza_99
nanWhen you want to compare 2 booleans to see if they are different220501T190823Ztouka
nan210720T094107ZATO
nan220315T033317Zjixperso
nan220314T215717ZJoao-3
nan220225T202821ZTRG078
nanTo convert a 2D list to a 1D flat list220225T031201ZDialFros
nan220120T210111Zpxeger
nan211218T015503Zpxeger
nan211111T155912Zpxeger
nan180109T222911Zxnor
nanSpecial characters in string literals210210T230843Zxnor
nan210916T075422Zxnor
nan161002T033640Zxnor
001Shorten while210831T202905Zdingledo
nan150626T181436Zxnor
nan210726T045538Zdingledo
nanUse a=b=c=0 instead of a110129T185200Zmoinudin
nan191116T134745Zbfontain
nan150217T072941ZSp3000
nan210413T171638ZRyan Lau
nanWhen you want to use map with list then cast it to list210316T165225ZHK boy
nan160121T045827Zxnor
nan110128T000533ZJPvdMerw
nan150518T220247Zxnor
nanPrinting the elements of a list201215T033930Zvrintle
nan200929T093502ZSisyphus
nan200612T112330Zuser9572
nan200509T205029Zdingledo
nan161013T143048Zxnor
nan191016T000444Zxnor
nan190217T014409Zxnor
nanNote The below makes sense only in the program is scored as characters190907T213627ZPetar Do
nan190907T074003Zxnor
nan190826T135117Zuser8505
nan190811T055547Zuser8505
nan190510T222531ZErik the
nan190427T223957Zxnor
nan181212T220240ZSparr
nanIn Python181114T002252Zcobaltp
nan181022T094822ZTim Rija
nan180823T055434ZChas Bro
nan180730T002616ZEsolangi
nan180724T002719Zxnor
nan180705T094923Zuser2027
023To assign to a tuple160610T075758ZErik the
nanLarge hard coded numbers can be represented in larger bases180622T202914Zmypetlio
nan141101T054124Zxnor
nan151214T120748ZTim Pede
nanUse Splat * to pass a bunch of single character strings into a function180413T182720Zhyperneu
nan180220T210956Zxnor
nan180112T224431Zfejfo
nan180103T180833Zlynn
nan171222T204955Zfejfo
nan110128T000555Zmoinudin
nan170119T071952ZG B
nan171024T082126ZNeil
035If transforming from list to a tuple or set to a set170904T101215ZBlue
nan170825T151313ZBite cod
nan170825T144327ZBite cod
nan170825T143929ZBite cod
nan170825T143151ZBite cod
nan151118T032731Zquintopi
nan131207T072637ZStrigoid
nanAccess list170803T144429ZDead Pos
nanIf you're drawing161015T235640ZAlbert R
nan150604T124342ZTim Rija
083Store 8bit numbers compactly as a bytes object in Python 3150612T040903Zxnor
nan161216T091505Zkon psyc
nanWhen mapping a function on a list in Python 3161119T222310ZTuxCraft
nanBooleans are integers161114T184822Zuser4594
nan151003T075809Zxnor
nan161105T002655Zxnor
nan160302T200443Zlynn
nan160825T193028Zxnor
nan160801T040910Zxnor
nan150117T140934ZJakube
nan150921T174653ZJuan Cor
nan160414T161528ZRichie L
nan160304T030701Zcat
002cmp in Python160302T204606Zmbomb007
nan160113T030827ZCyoce
nan141125T093019ZSp3000
nan160216T101007ZSp3000
nan151130T030522ZJ Atkin
nan110218T104732Zgmunkhba
nan160201T005833ZDennis
nan160127T200652ZMorgan T
nanFor integer n140910T033701Zxnor
nan150507T231336Zxnor
nan151130T005441ZJ Atkin
nan151117T052824Zquintopi
003Printing a string without a trailing newline in Python151110T093248ZSp3000
nan151023T053853Zxnor
nan151023T042512Zxnor
nan150525T005813ZSp3000
nan150705T122411ZSp3000
nan150418T151026ZSp3000
nan150530T090107Zxnor
nanInstead of rangex120304T213210ZBlazer
nan110627T020600Zgnibbler
nan150717T221851Zaditsu q
nan111221T071056ZJBernard
nan150705T122612ZSp3000
nan150705T120746ZSp3000
nanWhen squaring single letter variables150629T101426ZBeta Dec
nan150626T160857ZSp3000
nan150519T021033ZSp3000
nan150622T215754Zxnor
nan150616T205442Zxnor
nan150612T033504Zxnor
nan150525T074905ZSp3000
nan150423T081334Zuser3340
nan150423T055324Zxnor
nan150421T052607Zxnor
nanWhen using Python 3150419T040710ZJustin
nanIf you're using a builtin function repeatedly110128T000828Zmoinudin
003Extended iterable unpacking "Starred assignment"141202T151758ZSp3000
nan141122T010009Zxnor
nan141122T005129Zxnor
nan110203T131249Zgnibbler
nan141107T091257Zxnor
nan110128T000712ZChampo
nan141101T052026Zxnor
nanIf you are doing something small in a for loop whose only purpose is to invoke a side effect pop141025T054650ZJustin
nanYou can use default arguments of a function to save some indentation140821T163007ZFalko
nan140926T024359ZDLosc
nan131206T235352ZJustin
nan140401T182647ZJustin
nan140925T222736ZClaudiu
nan140928T084335ZBeta Dec
nan131018T062235ZCoding m
001If you rely on data mostly for kolmogorovcomplexity problems140925T223022ZClaudiu
nan140416T200505ZEyrofire
nanFor ages it bothered me that I couldn't think of a short way to get the entire alphabet. If you use range enough that R=range is worth having in your program140414T145433Zundergro
nanRun your code through an spaceremover140405T163710Zɐɔıʇǝɥʇu
nanIf you need to import a lot of modules you can reassign __import__ to something shorter140320T092540ZJustin F
nanWhen you have two boolean values131220T065322ZJustin
001If you represent boolean values as numbers you can save characters. This is especially true for using 1 as True.140121T044025ZJustin
nan140111T191716ZAMK
nan140108T234434ZTim Rija
nan140106T002518ZTimtech
nanBe aware of all140105T234014ZMartin T
nan131215T185224ZWasi
nan110703T052924Zboothby
nan110627T234601Zrplnt
nan110429T234114Zcemper93
003Just found out two new things. First110203T233216ZChampo
nan110203T203222Zgnibbler
nan110203T131847Zgnibbler
nan110203T131012Zgnibbler
002Sometimes you can use Python's execstatement combined with string repetition110128T001451ZJPvdMerw
nanIf you're doing somewhat more complex golfing that require something from the standard library to be used a lot110128T003744ZRafe Ket
nan110128T002641Zmoinudin
nan110128T000017ZJPvdMerw
nan110128T000212ZAlexandr

Integer ceiling division with no repeated terms and no extra parentheses fighting operator precedence

You have n, the numerator, and d, the denominator, or an expression, a+b as the denominator. Floor division is trivial:

n//d      # 4 characters. On Py2, n/d works, but Py2 is dead, move on
n//(a+b)  # 8 characters if denominator is expression with operator that is lower precedence
          # than division (or equal and same associativity), dumb parens

The naive approaches to ceiling division is one of:

math.ceil(n/d)      # 14 characters, and needs an import. Wrong if inputs large enough to hit
                    # C double integer representation limits (~53 bits)
math.ceil(n/(a+b))  # 18 characters; bad, but at least the denominator being an expression
                    # didn't make it proportionately worse

(n+d-1)//d          # 10 characters. No import needed, no C double precision limitations
                    # Repeats d twice though, so if d is a more complicated expression...
(n+a+b-1)//(a+b)    # 16 characters, and gets worse if d is more complicated or involves
                    # operators with precedence below +/-

As mentioned off-hand in another answer, you can turn floor division into ceiling division with:

-(-n//d)        # 8 characters, shortest so far, and it only uses each term once, so...
-(-n//(a+b))    # 12 characters (whew, only paying for d expression once again)

but there is still one more optimization to be had. Unary negation is too high precedence, so we needed a second set of parentheses to separate negation of the numerator from the negation of the result of floor division (getting us ceil division as an end result). That's too much. But thankfully, subtraction is lower precedence than unary negation, so we can just subtract from zero, and get:

0--n//d      # 7 characters! Only three more than floor division!
0--n//(a+b)  # 11 characters, still only use d term once!

This is probably one of the only times Python code golfers are glad that Python doesn't offer a -- decrement operator; since it doesn't exist, each - is separate, the first is a subtraction operand (relatively low precedence), the second unary negation (very high precedence), so no parentheses are needed; unary negation attaches before floor division, subtraction after, achieving ceiling division at the cost of one 0, instead of open and close parentheses.

(Destructively) Iterate any iterable in reverse

for x in s[::-1]:f(x)

can shorten to:

while s:f(s.pop())

when s is a list and destructive iteration is acceptable. But if you need to use the value multiple times, even with the walrus, this doesn't work so hot:

for x in s[::-1]:f(x);g(x)

while s:x=s.pop();f(x);g(x)  # Longer!
while s:f(x:=s.pop());g(x)   # Same length, and := precedence means it doesn't always work in larger expressions

And of course, pop calls don't work at all when s isn't already a list. In Python 3 though, you can use unpacking to do the pop work with fewer characters and it works on things that aren't lists (though they become a list after the first loop):

for x in s[::-1]:f(x);g(x)
while s:*s,x=s;f(x);g(x)

which shaves two characters, and (since it's already doing top-level statement work) doesn't have the issues with precedence in larger expressions that the walrus has.

Even for the single expression case, this can be useful:

for x in s[::-1]:f(x) # Works on any sequence
while s:f(s.pop())    # 3 characters shorter, but works only on lists, and only lets you use the value once unless assigned at higher cost
while s:*s,x=s;f(x)   # Only 2 characters shorter, but works on *any* iterable

Since the minimal number of characters to convert iterables to a list is 2-3 (depending on use), paying one extra character to avoid the conversion can be worth it.

Conditionals can be lengthy. In some cases, you can replace a simple conditional with (a,b)[condition]. If condition is true, then b is returned.

Compare

if x<y:return a
else:return b

To this

return(b,a)[x<y]

Use 0*9e999 instead of float('NaN')

Probably a pretty niche tip, but a quick way to save 5 bytes on any program that needs NaN as a constant. Plus it's still shorter even if it requires padding by spaces or brackets.

Appending to a list

Suppose you have x as a list and y as a value. You want to append y to x.

You can do this:

x+=y,#add y to the end of x, 5 bytes
#instead of
x+=[y]#add y to the end of x, 6 bytes

If z is also a value and you want to append y and z to x, do this:

x+=y,z#add y to the end of x, 6 bytes
#instead of
x+=[y,z]#add y to the end of x, 8 bytes

Verify

Use perm instead of factorial

The doc for perm is here:

math.perm = perm(n, k=None, /)
    Number of ways to choose k items from n items without repetition and with order.

    Evaluates to n! / (n - k)! when k <= n and evaluates
    to zero when k > n.

    If k is not specified or is None, then k defaults to n
    and the function returns n!.

perm is shorter and does the same thing as factorial when there is only 1 argument.

Use **.5 instead of math.sqrt()

This is a very useful tip, especially if square roots are the base of your answer.

Instead of

from math import*
x=sqrt(4)

which is 27 bytes, we can simply use

x=4**0.5

Golfed, of course, it's

x=4**.5

saving 20 bytes!

Note that this trick can be used for finding any root. Here is a function that does this:

lambda x,y:x**(1/y)

Use slicing when try to return single element list with-in and & or

We all known that following two statements are the same. So we prefer to use and-or in place of if-else when possible.

[v]if p>0else f(x)
p>0and[v]or f(x)

But whenever the return value is a single element in array, it can be further shorten as

[v][:p]or f(x)

The same idea may apply to multiple different conditions:

a>0and[v]or f(x)
(a>0)*[v]or f(x)
a*[v]or f(x) # if `a<=1` or dupe is acceptable
[v][:a]or f(x)

a<0and[v]or f(x)
[v][:-a]or f(x)

a==0and[v]or f(x)
[v][a*a:]or f(x)

Repr trick

Suppose you are using Python 3. You can use '%r'%a instead of repr(a):

>>> a=456
>>> repr(a)
'456'
>>> '%r'%a # 1 byte shorter
'456'

Note: In Python 2, you should use `a`.

Although python doesn't have very golfable switch statements (the match/case syntax since Python 3.10), you can emulate them with dictionaries. For example, if you wanted to golf this:

match a:
 case 1: runCodeOne()
 case 2: runCodeTwo()
 case 3: runCodeThree()
 case _: runDefault()

You could use if statements, or you could use one of these:

# Code as strings
exec{1:"runCodeOne()",2:"runCodeTwo()",3:"runCodeThree()"}[a]

# Functions with non-consecutive indices
{1:runCodeOne,4:runCodeFour,30:runCodeThirty)[a]()

# Functions with consecutive indices
# (you can't add a default value)
(0,runCodeOne,runCodeTwo,runCodeThree)[a]()

# Code as strings (and default code)
exec{ <same as before> }.get(a,"runDefault()")

# Run functions (and default function)
{ <same as before> }­.get(a,runDefault)()

This can be used to condense return statements:

# Before
def getValue(k):
 if k=='blah':return 1
 if k=='foo':return 2
 if k=='bar':return 3
 return 4

# After
# getValue = ...
lambda k:{'blah':1,'foo':2,'bar':3}.get(k,4)

Signum Function

Python doesn't have a nice signum built-in, even though its a very useful function for golfing. It takes a lot of bytes to use math.copysign or numpy.sign once you include the imports, and the latter doesn't even return ints, so you waste even more bytes if you need to use it in a list index, for example.

Here's a decent version you can use in that one answer where you really need integer signs multiple times:

s=lambda x:(x>0)-(x<0)

As per Jakque, in Python 2, you can use the cmp function.

A common pattern is to use list(map(lambda c: c.func(), iterable)). This can be shortened to list(map(<c's type>.func, iterable)). For example: list(map(lambda c:c.strip(), lines)) can be shortened to list(map(str.strip, lines))

Multiline Integer Inputs, works in Linux and Windows

This may be much shorter for Python3 and inputs as integer

a,b,c=map(int,open(0))

For example expected input is:

23
45
56

The above golf code will assign respective integer values a=23, b=45, c=56

If inverting result is fine:

a==123or b==123  # 15 bytes
123in[a,b]       # 10 bytes
a!=123!=b        #  9 bytes

Another tip: this is a pretty useful (but rarely useable) alternative ternary operator which we use in Scratch: * and +. This uses the fact the booleans are equal to 0 and 1, and the rules of multiplying, but can only be used in limited situations.

For example, in string manipulations, you can use these. I used this in my code.golf submission:

for i in range(1,101):print(f'{i}'*bool(i%3and i%5)+'Fizz'*(i%3==0)+'Buzz'*(i%5==0))

These can be sometimes long, so you can only use in limited situations. Note that string conversions may be necessary, as used in f'{i}', thus making this impractical with multiple datatypes.

This is also dangerous in recursive solutions, as all the conditions will be checked (so it doesn't terminate at a True value, thus recursing unnecessarily; the exact opposite of a short-circuit operator).

So in factorials, this will fail to RecursionError:

x=lambda n:n*(x(n-1)*(n!=1)+1*(n==1))

EDIT: It turns out that using this with and or or can actually solve the short-circuit problem mentioned above. See this as an example.

And for the factorial example (25 bytes):

x=lambda n:n<2or n*x(n-1)

Check if a number is a power of 2

Check whether a positive integer n is a perfect power of 2, that is one of 1, 2, 4, 8, 16, ..., with any of these expressions:

n&~-n<1
n&-n==n
n^n-1>=n
2**n%n<1

The third expression also works for n==0 giving False. The last is easy to modify to checking for, say, powers of 3.

Should you set variable?

This is perhaps already be posted but I could not find it with an explanation.

gsetn = lambda n, k, c=3: n+c < (n-1) * k
gset = lambda n, s, c=3: gsetn(n, len(s), c)

gset(3,'range')       # == True
gsetn(3, 4)           # == True

The cost of using f of length k n times is nk and if it is set, the cost is n+cost of setting. So if f is used n times it is worth setting if $$ n+c+k < n\cdot k\Leftrightarrow n+c < (n-1)\cdot k. $$ Typically it costs x=+k+\n(or ;) = 3 + k to set the variable. Example:

len('r,a,s=range,abs,sum;') == len('range')+len('abs')+len('sum')+3*3

But, it could be different:

from math import factorial as f

Use Annotations to save on indentation

Hurry up before this feature goes away

If you have code like this:

a:b = c

Is syntactically equivalent to

a = c
__annotations["a"] = b

Note that if b is a expression, it can be evaluated. You can use this for side effects, for example consider this python quine:

c:print(c%c)="c:print(c%%c)=%s"

In this case, this is the exact same length as

c="c:print(c%%c)=%s"
print(c%%c)

However, in a indented context, it can save some bytes:

if abcd:
   for defg in hijk:k:print(k(k))=eval(input())

Saves 5 bytes over:

if abcd:
    for defg in hijk:
        k=eval(input())
        print(k(k))

Collapse two numerical loops into one

Say you're iterating over the cells of an m*n grid. Instead of two nested for loops, one for the rows and one for the columns, it's usually shorter to write a single loop to iterate over the m*n cells of the grid. You can extract the row and column of the cell inside the loop.

Original code:

for i in range(m):
 for j in range(n):
  do_stuff(i,j)

Golfed code:

for k in range(m*n):
 do_stuff(k/n,k%n)

In effect, you're iterating over the Cartesian product of the two ranges, encoding the pair (i,j) as x=i*n+j. You've save a costly range call and a level of indentation inside the loop. The order of iteration is unchanged.

Use // instead of / in Python 3. If you refer to i and j many times, it may be shorter to assign their values i=k/n, j=k%n inside the loop.

Long numbers to 1e_

I'm not sure if this has been mentioned before (likely), so either I'm going crazy or I'm blind.

Long numbers like 10000 can be written as 1e4 for short. Do note that using 1e_ gives a decimal, not a integer, so 1e4 in fact gives 10000.0, so be wary when doing stuff like:

for x in range(1,1e4):print(x%5)

which gives an error since when using range you have to use integers.

Python 2 and 3 differences

A recent challenge pushed me to search for differences in two major versions of Python. More precisely, code that returns different results in different versions. This might be helpful in other polyglot challenges.

  1. Strings and bytes comparison
  1. Rounding (Luis Mendo answer)
  1. Division (Jonathan Allan answer)
  1. Suggestions?

Instead of not in, use in with ^1 or 1-

Often, it helps to replace a not in b with (a in b)^1. By themselves,it doesn't save any bytes, but it often means that you can remove whitespace:

For example, if a not in b: can just be if(a in b)^1: to save a byte.

You can use list checking instead of using ors in a clause statement.

e.g. instead of using

if i % 3 == 0 or i % 5 == 0 or i % 7 == 0 ...:
# Golfed:
if i%3==0or i%5==0or i%7==0 ...:

use

if 0 in [i % 3, i % 5, i % 7, ...]:
# Golfed:
if 0in[i%3,i%5,i%7,...]:

This saves around 2-3 characters per condition, but can only be used in certain circumstances.

The best way to check whether is a number even or not

Usually you do it this way (6 bytes):

n%2==0

But you can reduce it to 5 bytes:

n%2<1

And even 4 bytes:

~n&1

Bonus tip: when you use if you can ignore spacebetween if and ~n&1 this way:

if~n&1:

Multiple if statements in comprehensions

If you need to keep multiple conditions inside comprehension, you can replace and with if to save a byte each time.

Works in Python 2 and 3.

[a for a in 'abc'if cond1()and cond2()or cond3()and cond4()and cond5()]
[a for a in 'abc'if cond1()if cond2()or cond3()if cond4()if cond5()]

Try it online!

Use string substitution and exec to deal with long keywords like lambda that are repeated often in your code.

a=lambda b:lambda c:lambda d:lambda e:lambda f:0   # 48 bytes  (plain)
exec"a=`b:`c:`d:`e:`f:0".replace('`','lambda ')    # 47 bytes  (replace)
exec"a=%sb:%sc:%sd:%se:%sf:0"%(('lambda ',)*5)     # 46 bytes  (%)

The target string is very often 'lambda ', which is 7 bytes long. Suppose your code snippet contains n occurences of 'lambda ', and is s bytes long. Then:

From a plot of bytes saved over plain for these three options, we can see that:

For other cases, you can index the table below:

          1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 (occurences)
       +---------------------------------------------------------
     3 |  -  -  -  -  -  -  -  -  -  -  -  -  -  -  r  r  r  r  r  
     4 |  -  -  -  -  -  -  -  -  -  r  r  r  r  r  r  r  r  r  r  
     5 |  -  -  -  -  -  -  -  r  r  r  r  r  r  r  r  r  r  r  r  
     6 |  -  -  -  -  -  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
     7 |  -  -  -  -  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
     8 |  -  -  -  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
     9 |  -  -  -  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
    10 |  -  -  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
    11 |  -  -  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
    12 |  -  -  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r = replace
    13 |  -  -  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r   % = string %
    14 |  -  %  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r   - = do nothing
    15 |  -  %  %  %  %  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
  (length)

For example, if the string lambda x,y: (length 11) occurs 3 times in your code, you're better off writing exec"..."%(('lambda x,y:',)*3).

Use `n` to convert an integer to a string instead of using str(n):

>>> n=123
>>> `n`
'123'

Note: Only works in Python 2.

List comprehension.

shortList = []
for x in range(10):
    shortList += [x * 2]

can be shortened into

shortList = [x*2 for x in range(10)]

Or even shorter:

shortList = range(0,20,2)

Use the walrus operator := in list comprehension to store the previous value of the iterable

Instead of the convoluted

f=[s[i]for i in range(len(s))if s[i-1]!=s[i]]

You can use

e=""
f=[c for c in s if e!=(e:=c)]

Which saves 11 bytes in this example. Care needs to be taken that e is reassigned after being evaluted. It also needs to be initialised before the list, which is quite easy to do with default function arguments

When you want to compare 2 booleans to see if they are different, it's preferable to use ^ (XOR) rather than != (it can save one byte)

Example with: a: bool and b: bool

if a!=b: # 8 bytes
if a^b: # 7 bytes

Combine assignments of reused values with unused for-loop variables

If you need to loop a number of times but you don't care about the iteration variable, you can co-opt the loop to assign a variable.

r=reused;for _ in"_"*n:stuff
r=reused;exec("r;"*n)                          # [note 1]
r=reused;exec"r;"*n                            # [note 1]; Python 2 only
for r in[reused]*n:r

lambda args:((r:=reused)for _ in"_"*n)         # generally needs parentheses
lambda args,r=reused:(r for _ in"_"*n)         # only works with constants
lambda args:(r for r in[reused]*n)

This is generally a more versatile approach for assignment than the := operator or using default arguments of functions, because it supports assigning to attributes .x, subscripts [x], and unpacking with * or ,.

(stuff+(a[0]:=value)for _ in"_"*n)                   # syntax error
(stuff+a[0]for a[0]in[value]*n)                      # works, and shorter!

(stuff+a+b for*a,b in[value]*n)                      # works!

The only pitfall is that scope inside comprehensions is sometimes quite confusing, because the body of the comprehension is compiled as a separate implicit function.

Taken from @xnor's use of it here.

[note 1]: and longer if backslashes/quotes/newlines/... need to be escaped inside the string


This is a bot account operated by pxeger. I'm posting this to get enough reputation to use chat.

From what i learned:

  1. Encode your long codes to base64 and use eval to run them: eval(ENCODEFUNC(CODE)). Something like zlib has half the size of b64 but there are even more efficient hash function that you can look up.
  2. Use ternary operators and lambdas.
  3. If the the task you trying to accomplish is a trivial thing then probably there is a builtin function for it somewhere.
  4. Always look for a case for using list comprehensions and generators stuff.

Do a ternary operator when you can.

Factorial example:

def f(x):return 1 if x==1 else x*f(x-1)

!= can be replaced with -
here is a example

n=int(input())
if n!=69:
 print("thanks for being mature")

instead of using != you can use -
after that it should look like this

n=int(input())
if n-69:
 print("thanks for being mature")

To convert a 2D list to a 1D flat list, you can do sum(2d_list,[]) instead of the long way of import numpy;list=list.flatten(), which requires to create a numpy.array at the start as well, which is way longer than the first one

0in instead of not all

(or, under DeMorgan's Law, any(not ...))

not all(...)
~-all(...)  # shorter than `not`, and with more forgiving precedence
0in(...)
not all map(f,a)
0in map(f,a)  # the reduction is more significant here because you can omit the parentheses

This only works if the falsey values in the ... sequence are actually False (or 0/0.0/etc.) (not []/""/{} etc.).

1in instead of any

This one isn't shorter with a comprehension:

any(f(x)for x in a)
1in(f(x)for x in a)

But it sometimes saves bytes with other kinds of expression by letting you omit the parentheses:

any(map(f,a))
1in map(f,a)

This has a similar truthiness-related caveat to the above, though.


Notes

These might sometimes have less favourable precedence, because they use the in operator. However, if you're combining this with a comparison you may be able to make additional use of this tip about comparison condition chaining.

You can also use these if you want the entire for-comprehension in any/all to always be fully evaluated:

any([... for x in a])
1in[... for x in a]

This one's rare, but if you need to evaluate and discard an extra expression for every item in a comprehension, you could use a dictionary here at no extra cost:

1in[(condition,side_effect)[0]for x in a]
1in{condition:side_effect for x in a}

because dict's in checks only the keys.

Access static methods on instances

If you're accessing a static method or class method, for example int.from_bytes or dict.fromkeys, you can also still access them on instances of that class - it doesn't have to be on the class itself. It's very often shorter to do this:

int.from_bytes(...
0 .from_bytes(...

dict.fromkeys(...
{}.fromkeys(...

Often you already have an instance of that class stored in a one-letter variable, so it can be even shorter:

x.from_bytes

It doesn't matter what value x is, and it isn't changed.

The shortest infinite for comprehension

You may know the trick to easily create an infinite generator using the two-argument form of iter:

(... for _ in iter(lambda:0,1))

where 0 and 1 can be any two non-equal values.

As @ovs once pointed out to me, you can replace lambda:0 with int, because int returns 0 when called with no arguments.

(... for _ in iter(int,1))

However, we can do one byte better!:

(... for()in iter(set,1))

This uses the fact that () is a valid L-value (assignment target) in Python as long as the RHS is an empty sequence, and set returns an empty set when called with no arguments.

You can also use str instead of set for the same byte count.

List all substrings

You can generate the nonempty contiguous substrings of a string s with a recursive function (Python 3 for [*s]).

40 bytes (TIO)

f=lambda s:[*s]and[s]+f(s[1:])+f(s[:-1])

This will repeat substrings multiple times even if each substring appears once. You can making this a set to remove duplicates. This won't run if s is a list instead of a string, but a tuple will work.

40 bytes (TIO)

f=lambda s:{*s}and{s}|f(s[1:])|f(s[:-1])

Or, you can do this to make a list where each substring appears one for each time it's present:

46 bytes (TIO)

f=lambda s,b=-1:[*s]and[s]+f(s[1:],0)+f(s[:b])

Thanks for loopy walt for the s[:b] optimization.

This can be used to sum over some expression g over all substrings, for instance to count nonempty substrings with some Boolean property g.

48 bytes (TIO)

f=lambda s,b=-1:s>""and g(s)+f(s[1:],0)+f(s[:b])

Special characters in string literals

When you write a quoted literal string in your code, perhaps to compress a big blob of data, certain characters must be replaced by a two-character escape sequence.

Null byte \0 (ASCII 0)

The null byte can't be present verbatim in Python code. Write it as \0.

Newline \n (ASCII 10)

An actual newline \n can't appear in a string literal because the Python lexer will read it and think the line has ended without closing the initial quote. But, a triple-quoted string like '''stuff''' or """stuff""" may contain newlines. This saves bytes with 5+ newlines, which can be useful in ASCII art.

Carriage return \r (ASCII 13)

A carriage return always needs escaping as \r. Though allowed in a triple-quoted string, a literal \r is misread as a newline \n.

Quotes " (ASCII 34) and ' (ASCII 39)

A single-quoted string can contain double quotes like '"', but must escape single-quotes like '\'', and vice-versa for double-quoted strings. Choose whichever option leads to less escaping.

A triple-quoted string is OK with unescaped quotes of the same type like '''it's'''. But, having quotes at the start and end or three-in-a-row can confuse the lexer into giving a SyntaxError.

Backslash \ (ASCII 92)

A backslash can be escaped as \\. But, Python allows just writing \ if it's followed by a character that can't make it an escape sequence. This is any character not in abfnrtvx0123456789"'\ or literal newline \n.

You can use a r-prefixed raw string like r'\n' to ignore most escape sequences, so r'\n' is just a backslash followed by a letter n and r'\\' is two backslashes. Quote characters still get escaped but don't consume the backslash, so r'\'' is backslash then single-quote. This can cause complications: r'\', r'\\\', and r'\\'' all give SyntaxError.


For reference, the special characters are ASCII values [0, 10, 13, 39, 34, 92]. When doing compression, you might tweak your method to avoid hitting these values.

Some weird characters can be written verbatim without escaping, such as:

StackExchange posts won't render these, but Python clients and TIO should handle them fine. Here they are for copy-pasting.

Characters with ASCII codes 128 and up can't be included in Python 2 code without a extra line declaring an encoding like this. Python 3, though, handles them fine, including multibyte Unicode characters.

Trig without imports

You can compute cos and sin without needing to import math by using complex arithmetic. For an angle of d degrees, its cosine is

(1j**(d/90)).real

and its sine is

(1j**(d/90)).imag

Here, 1j is how Python writes the imaginary unit \$i\$. If your angle is r radians, you'll need to use 1j**(r/(pi/2)), using a decimal approximation of pi/2 if the challenge allows it.

If you're curious, this all works because of Euler's formula:

$$i^x = (e^{i \pi /2})^x = e^{i \pi /2 \cdot x} = \cos(\pi/2 \cdot x) + i \sin(\pi /2 \cdot x)$$

Object method as answer

Your submission can be a method of an object

range(123,790,111).count

This defines an anonymous function much shorter than

lambda n:range(123,790,111).count(n)

The object method is a valid function that meets our definition. For example, it could be bound and called

f=range(123,790,111).count
print f(99)

Because it avoids a costly lambda, this saves characters even rewriting from

lambda n:n in range(123,790,111)

Consider using an object method when your solution is a simple two-input function of your input and some concrete object. You can use dir() to get a list of methods of an object. Note in particular methods like .__add__ that are called for an operator like +. Most infix operators correspond to a method.

Other examples:

"prefix{}suffix".format
lambda s:"prefix"+s+"suffix"

2 .__rpow__    #Space for lexer
lambda n:n*n

[0,0].__le__
lambda l:[0,0]<=l

You can even sometimes save bytes with two input by currying. For example, compare

lambda l:expression_in_l.count
lambda n,l:n in expression_in_l

where expression_in_l produces a list with no duplicates and has favorable spacing and precedence.

Shorten while 1

It is possible to shorten a while 1: by replacing the 1 with an existing expression inside of the loop body. Common ways to make use of this in Python 3 include embedding

while 1:print(x);...
# vs
while[print(x)]:...
while 1:x>1==print(x);...
# vs
while[x>1==print(x)]:...
while 1:x=1;...
while x:=1:...

In general, any expression (one that returns a value), can be used as the while condition to save a byte or two. Often it's necessary to wrap the expression in [] to ensure it maintains a truthy value.

Length tradeoff reference

I've think it would be useful to have a reference for the character count differences for some common alternative ways of doing things, so that I can know when to use which. I'll use _ to indicate an expression or piece of code.

Assign to a variable: +4

x=_;x
_

So, this breaks even if you

Assign variables separately: 0

x,y=a,b
x=a;y=b

Expand lambda to function def: +7

lambda x:_
def f(x):return _

Generically, if you're def to save an expression to a variable used twice, this breaks even when the expression is length 12.

lambda x:g(123456789012,123456789012)
def f(x):s=123456789012;return g(s,s)

STDIN rather than function: +1

def f(x):_;print s
x=input();_;print s

Use exec rather than looping over range(n): +0

for i in range(n):_
i=0;exec"_;i+=1;"*n

Apply map manually in a loop: +0

for x in l:y=f(x);_
for y in map(f,l):_

Apply map manually in a list comprehension: +8

map(f,l)
[f(x)for x in l]

Apply filter manually in a list comprehension: +11

filter(f,l)
[x for x in l if f(x)]

Import versus import single-use: +4*

import _;_.f
from _ import*;f

Thanks to @Sp3000 for lots of suggestions and fixes.

Long function names

Here's a trick to shorten long function names. The basic idea is to fetch the name by using dir(). This would return the name as a string, so we must follow it with an eval to make it usable. Below is an exaggerated example from the itertools module:

from itertools import*

combinations_with_replacement('ABC',2)
eval(dir()[7])('ABC',2)

In the minimal case, if the function name is 15 bytes or longer, there's a chance that it can still save bytes. This is assuming, that the name can be accessed by dir with a single-digit index:

???????????????()
eval(dir()[?])()

Use a=b=c=0 instead of a,b,c=0,0,0. (Note that this uses the same instance for each variable, so don't do this with objects like lists if you intend to mutate them independently)

Use a,b,c='123' instead of a,b,c='1','2','3'.

dict.get as a first-class function

# all keys in the dict G with a truthy value
[k for k in G if G[k]]
filter(G.get,G)

# all keys in the dict G with a falsy value
[k for k in G if not G[k]]
G.keys()-filter(G.get,G)

{…,**d} or a|b to merge dicts in Python

# merge two dicts
a={…}
b={…}
# Python <3.9
merged={**a,**b} # the order lets you decide which overrides which
# Python ≥3.9
merged=a|b

# set a defaut value
G.setdefault(a,1)
G[a]=G.get(a,1)
# Python <3.9
G={a:1,**G} 
# Python ≥3.9
G={a:1}|G

Extract elements from a list using ::

# This is a very specific tip when you want to get both an element at
# the near beginning of a list and one somewhere near the end.
# For example, let's assume you want to take the elements at indices i=6 and j=37
# from a list L of length l=40 (it works only if i+j*2<l)

# ok
a=L[5];b=L[36]
# equivalent
a,b=L[5],L[36]
# 36 = 5 + 31
a,b=L[5::31]

Set literals

set() is 5 chars just to create an empty set. If you can have an initial element e, you can save 2 chars with {e}.

Generators instead of comprehension lists in function calls

# assuming the function iterates on its argument
f([x**2 for x in range(4)])
f(x**2 for x in range(4))

Arithmetic tricks

Here are some arithmetic tricks which are either shorter or are more useful due to precedence rules.

Assumptions                  Version 1        Version 2
-------------------------------------------------------------------
n >= 0 float                 n==0             0**n
n >= 0 integer               n==0             1>>n
n >  0 integer               n!=1             1%n
n >  0 integer, Python 2     n==1             1/n
n, m float                   n!=m             n-m

Checking if a boolean value is false and an integer is a specific odd integer

~True is ~1 is -2 and ~False is ~0 is -1

-1&int is always int

-2&int is always even

Therefore, despite operator order, ~bool&int==odd_int works fine.

It's shorter than all of these equivalents:

not bool and int==odd_int

-~bool and int==odd_int

-~bool&int==odd_int

When you want to use map with list then cast it to list, use * instead of list(...).

new_a=list(map(f,a))
new_a=[*map(f,a)]     # -3 char

Moreover, you also can convert some iterable things to list with saving 3 characters:

a=list("abc")
a=[*"abc"]
b=list(range(x,y))
b=[*range(x,y)]

Logical short-circuiting in recursive functions

A detailed guide

I had worked with short-circuiting and/or's for a while without really grasping how they work, just using b and x or y just as a template. I hope this detailed explanation will help you understand them and use them more flexibly.


Recursive named lambda functions are often shorter than programs that loop. For evaluation to terminate, there must be control flow to prevent a recursive call for the base case. Python has a ternary condition operator that fits the bill.

f=lambda x:base_value if is_base_case else recursive_value

Note that list selection won't work because Python evaluates both options. Also, regular if _: isn't an option because we're in a lambda.


Python has another option to short-circuit, the logical operator keywords and and or. The idea is that

True or b == True
False and b == False

so Python can skip evaluate b in these cases because the result is known. Think of the evaluation of a or b as "Evaluate a. If it's True, output a. Otherwise, evaluate and output b." So, it's equivalent to write

a or b
a if a else b

It's the same for a or b except we stop if a is False.

a and b
a if (not a) else b

You might wonder why we didn't just write False if (not a) else b. The reason is that this works for non-Boolean a. Such values are first converted to a Boolean. The number 0, None, and the empty list/tuple/set become False, and are so called "Falsey". The rest are "Truthy".

So, a or b and a and b always manages to produce either a or b, while forming a correct Boolean equation.

(0 or 0) == 0
(0 or 3) == 3
(2 or 0) == 2
(2 or 3) == 2
(0 and 0) == 0
(0 and 3) == 0
(2 and 0) == 0
(2 and 3) == 3
('' or 3) == 3
([] and [1]) == []
([0] or [1]) == [0]

Now that we understand Boolean short-circuiting, let's use it in recursive functions.

f=lambda x:base_value if is_base_case else recursive_value

The simplest and most common situation is when the base is something like f("") = "", sending a Falsey value to itself. Here, it suffices to do x and with the argument.

For example, this function doubles each character in a string, f("abc") == "aabbcc".

f=lambda s:s and s[0]*2+f(s[1:])

Or, this recursively sums the cubes of numbers 1 through n, so f(3)==36.

f=lambda n:n and n**3+f(n-1)

Another common situation is for your function to take non-negative numbers to lists, with a base case of 0 giving the empty list. We need to transform the number to a list while preserving Truthiness. One way is n*[5], where the list can be anything nonempty. This seems silly, but it works.

So, the following returns the list [1..n].

f=lambda n:n*[5]and f(n-1)+[n]  

Note that negative n will also give the empty list, which works here, but not always. For strings, it's similar with any non-empty string. If you've previously defined such a value, you can save chars by using it.

More generally, when your base value is an empty list, you can use the arithmetic values True == 1 and False == 0 to do:

[5]*(is_not_base_case)and ...

TODO: Truthy base value


TODO: and/or

Sometimes your Python code requires you to have 2 levels of indentation. The obvious thing to do is use one and two spaces for each indentation level.

However, Python 2 considers the tab and space characters to be different indenting levels.

This means the first indentation level can be one space and the second can be one tab character.

For example:

if 1:
 if 1:
	pass

Use map for side effects

Usually you use map to transform a collection

>> map(ord,"abc")
[97, 98, 99]

But you can also use it to repeatedly act on object by a built-in method that modifies it.

>> L=[1,2,3,4,5]
>> map(L.remove,[4,2])
[None, None]
>> L
[1, 3, 5]

Be aware that the calls are done in order, so earlier ones might mess up later ones.

>> L=[1,2,3,4,5]
>> map(L.pop,[0,1])
[1, 3]
>> L
[2, 4, 5]

Here, we intended to extract the first two elements of L, but after extracting the first, the next second element is the original third one. We could sort the indices in descending order to avoid this.

An advantage of the evaluation-as-action is that it can be done inside of a lambda. Be careful in Python 3 though, where map objects are not evaluated immediately. You might need an expression like [*map(...)] or *map(...), to force evaluation.

Printing the elements of a list, with spaces

Suppose we have to print a list as a string with spaces, like square of numbers upto 10. Then,

Instead of,

print(' '.join(str(i**2)for i in range(11))) # 44 chars

We can do,

print(*(i**2for i in range(11))) # 32 chars

Abuse == short circuiting

If you have:

Then you might be able to use == over or to save a byte.

Here's printing all numbers n under 100 that have f(n) less than 2:

# Naive
for n in range(100):f(n)<2and print(n)
# Invert condition
for n in range(100):f(n)>1or print(n)
# Use ==
for n in range(100):f(n)<2==print(n)

To set lots of variables to the same thing use:

# x is a list of the names of the variables you want and y is
# the value you want all of them to have
exec(("%s="*len(x))%tuple(x)+str(y))

Using exec to remove repeated print

This is not quite often applicable, but can save some bytes, especially in ASCII art. Take the following code, which prints the flag where n=4.

# 43 bytes                  |  ***
n=input()                   |  **
while~-n:n-=1;print'*'*n    |  *
print'|'                    |  |

Notice that we repeat print twice. We can remove this using exec in the following code, saving 3 bytes.

# 40 bytes
n=input()
exec"'*'*n;n-=1;print"*n+"'|'"

Iterate over adjacent pairs

It's common to want to iterate over adjacent pairs of items in a list or string, i.e.

"golf" -> [('g','o'), ('o','l'), ('l','f')]

There's a few methods, and which is shortest depends on specifics.

Shift and zip

## 47 bytes
l=input()
for x,y in zip(l,l[1:]):do_stuff(x,y)

Create a list of adjacent pairs, by removing the first element and zipping the original with the result. This is most useful in a list comprehension like

sum(abs(x-y)for x,y in zip(l,l[1:]))

You can also use map with a two-input function, though note that the original list is no longer truncated.

## Python 2
map(cmp,l[:-1],l[1:])

Keep the previous

## 41 bytes, Python 3
x,*l=input()
for y in l:do_stuff(x,y);x=y

Iterate over the elements of the list, remembering the element from a previous loop. This works best with Python 3's ability to unpack to input into the initial and remaining elements.

If there's an initial value of x that serves as a null operation in do_stuff(x,y), you can iterate over the whole list.

## 39 bytes
x=''
for y in input():do_stuff(x,y);x=y

Truncate from the front

## 46 bytes
l=input()
while l[1:]:do_stuff(*l[:2]);l=l[1:]

Keep shortening the list and act on the first two elements. This works best when your operation is better-expressed on a length-two list or string than on two values.


I've written these all as loops, but they also lend to a recursive functions. You can also adjust to get cyclic pairs by putting the first element at the end of the list, or as the initial previous-value.


The Python 3.8 "walrus" assignment expressions allow a short expression to give pairs, though with an extra initial element.

>>> p=''
>>> [(p,p:=c)for c in"golf"]
[('', 'g'), ('g', 'o'), ('o', 'l'), ('l', 'f')]

Math built-ins in 3.8

In addition to the famous walrus operator, Python 3.8 introduces useful new math features.

Modular inverse

The modular-power built-in pow(base, exp, mod) can now compute the modular inverse using exp=-1. This requires that base and mod are relatively prime integers.

>>> pow(38, -1, 97)
23
>>> 23 * 38 % 97 == 1
True

exp may be any negative integer, which lets you compute modular powers of the modular inverse.


The math library has useful new functions for combinatorics and distances. Access them with import math. Or, write from math import* to import them without the math., which is worth it if you write more than one call.

Combinatorics

Distances and square roots

Assignment expressions

Assignment expressions are a powerful language feature introduced in Python 3.8 (TIO). Use the "walrus operator" := to assign a variable inline as part of expression.

>>> (n:=2, n+1)
(2, 3)

You can save an expression to a variable inside a lambda, where assignments are not ordinarily allowed. Compare:

def f(s):t=s.strip();return t+t[::-1]
lambda s:s.strip()+s.strip()[::-1]
lambda s:(t:=s.strip())+t[::-1]

An assignment expression can be used in a comprehension to iteratively update a value, storing the result after each step in a list or other collection. This example computes a running sum by updating the running total t.

>>> t=0
>>> l=[1,2,3]
>>> print([t:=t+x for x in l])
[1, 3, 6]
>>> t
6

This can be done in a lambda with the initial value as an optional argument:

>>> f=lambda l,t=0:[t:=t+x for x in l]
>>> f([1,2,3])
[1, 3, 6]

This function is reusable: each call with start t back at 0.

Note: The below makes sense only in the program is scored as characters, not as bytes.

I haven't seen this, though somebody may have posted it somewhere.

I needed to have some long literal ASCII strings in the code so somehow shortening them (as characters, not bytes) would be beneficial. After some experiments I came up with what I call the "Chinese reencoding". I call it that way because ASCII characters mostly seem to be squashed in unicode code points that represent Chinese characters. You take an ASCII string S, encode it in bytes as ASCII, and then decode it in UTF16-BE, like that:

E=S.encode().decode('utf16-be')

The resulting string is half the length. It has to be big endian, as the reverse reencoding may not work - and on most systems the shorter 'utf16' is little endian. You also may need to add a character like space if the original string has odd length, but many times this is OK. Also, for non ASCII characters this does not save length, because they result in too big unicode code points that are represented in the liong form ("\uXXXX")

In you code, use the following:

[E].encode('utf16-be').decode()

in order to get the original longer string, where [E] is the literal shortened string. This costs 29 additional characters, so the original string has to be longer than 58, obviously.

One example - below is my 12 days of Christmas (it can be shortened additionally, but let's use that as an example):

for i in range(12):print('On the %s day of Christmas\nMy true love sent to me\n%s'%('First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth'.split()[i],'\n'.join('Twelve Drummers Drumming,+Eleven Pipers Piping,+Ten Lords-a-Leaping,+Nine Ladies Dancing,+Eight Maids-a-Milking,+Seven Swans-a-Swimming,+Six Geese-a-Laying,+Five Gold Rings,+Four Calling Birds,+Three French Hens,+Two Turtle Doves, and+A Partridge in a Pear Tree.\n'.split('+')[11-i:])))

It's 477 characters long. Let's apply the "Chinese" trick to the two longer string:

r=lambda s:s.encode('utf-16be').decode();for i in range(12):print('On the %s day of Christmas\nMy true love sent to me\n%s'%(r('䙩牳琠卥捯湤⁔桩牤⁆潵牴栠䙩晴栠卩硴栠卥癥湴栠䕩杨瑨⁎楮瑨⁔敮瑨⁅汥癥湴栠呷敬晴栠').split()[i],'\n'.join(r('呷敬癥⁄牵浭敲猠䑲畭浩湧Ⱛ䕬敶敮⁐楰敲猠偩灩湧Ⱛ呥渠䱯牤猭愭䱥慰楮本⭎楮攠䱡摩敳⁄慮捩湧Ⱛ䕩杨琠䵡楤猭愭䵩汫楮本⭓敶敮⁓睡湳ⵡⵓ睩浭楮本⭓楸⁇敥獥ⵡⵌ慹楮本⭆楶攠䝯汤⁒楮杳Ⱛ䙯畲⁃慬汩湧⁂楲摳Ⱛ周牥攠䙲敮捨⁈敮猬⭔睯⁔畲瑬攠䑯癥猬\u2061湤⭁⁐慲瑲楤来\u2069渠愠健慲⁔牥攮ਠ').split('+')[11-i:])))

That's 362, including the lambda (it happens to be worth it, as it is used twice).

Now, all code is mostly ASCII characters, so you may have already guessed that you can use that with exec. There is higher overhead - 43 chars for "exec(''.encode('utf-16be').decode())" (in addition to the whole compressed program) and you may need to double escape some escaped characters in your literal strings (like '\n' in mine has to become '\n'). As a bonus you can always easily add that one space. The compressed porogram looks like:

exec("景爠椠楮\u2072慮来⠱㈩㩰物湴⠧佮⁴桥‥猠摡礠潦⁃桲楳瑭慳屮䵹⁴牵攠汯癥\u2073敮琠瑯\u206d敜渥猧┨❆楲獴⁓散潮搠周楲搠䙯畲瑨⁆楦瑨⁓楸瑨⁓敶敮瑨⁅楧桴栠乩湴栠呥湴栠䕬敶敮瑨⁔睥汦瑨✮獰汩琨⥛楝Ⱗ屮✮橯楮⠧呷敬癥⁄牵浭敲猠䑲畭浩湧Ⱛ䕬敶敮⁐楰敲猠偩灩湧Ⱛ呥渠䱯牤猭愭䱥慰楮本⭎楮攠䱡摩敳⁄慮捩湧Ⱛ䕩杨琠䵡楤猭愭䵩汫楮本⭓敶敮⁓睡湳ⵡⵓ睩浭楮本⭓楸⁇敥獥ⵡⵌ慹楮本⭆楶攠䝯汤⁒楮杳Ⱛ䙯畲⁃慬汩湧⁂楲摳Ⱛ周牥攠䙲敮捨⁈敮猬⭔睯⁔畲瑬攠䑯癥猬\u2061湤⭁⁐慲瑲楤来\u2069渠愠健慲⁔牥攮屮✮獰汩琨✫✩嬱ㄭ椺崩⤩".encode('utf-16be').decode())

and it's 299 characters long. You can see some high code points can always appear. I have not found a way to eliminate them, as the added handling code is not worth the benefit.

This is a cheap trick, in fact, but it can always be applied on top of your solution when the program is longish and there are no or few non-ASCII characters. Often you can devise a custom encoding that can stuff more than two ASCII chars in an unicode one, but it is specific for the task.

Recursive functions that print

Functions are allowed to print as programs do. A recursive function that prints can be shorter than both a pure function and a pure program.

Compare these Python 2 submissions to make a list of iteratively floor-halving a number while it's positive, like 10 -> [10, 5, 2, 1].

# 30 bytes: Program 
n=input()
while n:print n;n/=2

# 29 bytes: Function
f=lambda n:n*[0]and[n]+f(n/2)

# 27 bytes: Function that prints
def g(n):1/n;print n;g(n/2)

Try it online!

The function that prints uses 1/n to terminate with error on hitting n=0 after having printing the desired numbers. This saves characters over the program's while and the pure function's base case, giving it the edge in byte count. Often, the termination can be shorter as part of the expression to print or the recursive call. It might even happen on its own for free, like terminating on an empty string when the first character is read.

The key property of our function here is that we're repeatedly applying an operation and listing the results at each step, in order. Additional variables can still be used this way by having them as optional inputs to the function that are passed in the recursive call. Moreover, because we're def'ing a function rather than writing a lambda, we can put statements such as variable assignments in its body.

Replace not with 1-

In python, the negation operator not wastes bytes, so we have to find a shorter way. Negation can be implemented as subtraction from 1 (obtained from my Keg experiece), which saves 1 byte. (Also, True and False can be alternatively represented as 1 and 0 internally, so this will not matter much.)

Compare this program:

lambda s:not(s[0]+s[-1]).isdigit()

With this program:

lambda s:1-(s[0]+s[-1]).isdigit()

Some straightforward tricks that might help:

and -> *
or -> +

I discovered a clever trick used here.

Instead of using the for loop to repeat multiple times, repeat exec multiple times.

p='+'
i=1
exec"print[p*i,i/9*p+'[>'+p*9+'<-]>'+i%9*p][i>20];i+=1;"*255

Compare this with

print"\n".join(">"+"+"*(i/16)+"[<"+"+"*16+">-]<"+"+"*(i%16)if i>31 else"+"*i for i in range(256))

Shortening a%b==a if b has a constant sign

For two expressions a and b, where each one results in an int (or long in Python 2) or float, you can replace these:

a%b==a

a==a%b

with these, if b is positive:

0<=a<b

b>a>=0

or these, if b is negative:

b<a<=0

0>=a>b

I'm presenting two expressions for each case because sometimes you may want to use one over the other to eliminate a space to separate expression b from an adjacent token. They both have the same precedence, so you're not usually going to need to surround the second expression with () if you don't need to do so to the first one.

This is useful if expression a is more than 1 byte long or b is negative, because it removes one occurrence of a from the expression. If \$a,b\$ are the lengths of expressions a and b respectively, and \$l\$ is the length of the original expression, the resulting expression will be \$l-a+1\$ bytes long. Note that this method is always going to be shorter than assigning expression a to a separate variable.

Example

For example,

(a+b)%c==a+b

can be replaced with

0<=a+b<c

for a total saving of 4 bytes.

Proof

Let's define the operator \$x\mathbin\%y\$ for \$x,y\in\mathbb Q\$.

Every rational number \$a\$ can be represented as \$a=bq+r\$, where \$q\in\mathbb Z,0\le r<|b|\$. Therefore, we can define an operator \$a\mathbin\%b\$, where the result has the same sign as \$b\$:

$$a=bq+r,q\in\mathbb Z,0\le r<|b|\\a\mathbin\%b=\begin{cases}\begin{align}r\quad b>0\\-r\quad b<0\end{align}\end{cases}$$

This represents the % operator in Python, which calculates the remainder of the division of two numbers. a % b is the same as abs(a) % b, and the result has the same sign as the divisor, b. For the \$a\mathbin\%b\$ operator, this equality holds:

$$(a\pm b)\mathbin\%b=a\mathbin\%b$$

Proof:

$$a=bq+r\leftrightarrow a\pm b=bq+r\pm b=(bq\pm b)+r=b(q\pm1)+r$$

Moreover, for \$b>0\$, we have:

$$a\mathbin\%b=a\leftrightarrow r=a\leftrightarrow0\le a<b$$

Proof for \$r=a\leftarrow0\le a<b\$:

$$0\le a<b\leftrightarrow0\le bq+r<b\leftrightarrow bq=0\leftrightarrow a=r$$

Similarly, for \$b<0\$, we have \$b<a\le0\$.

Therefore, \$a\mathbin\%b=a\leftrightarrow\begin{cases}\begin{align}0\le a<b\quad b>0\\b<a\le0\quad b<0\end{align}\end{cases}\$, or, equivalently, \$(0\le a<b)\lor(b<a\le0)\$.

Split into chunks

You can split a list into chunks of a given size using zip and iter, as explained in this SO question.

>>> l=range(12)
>>> zip(*[iter(l)]*4)
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]

Of course, substituting in l as zip(*[iter(range(12))]*4) gives the same result.

The 4 is the number of elements per chunk. If the length isn't a multiple of this, any elements in the remainder are not included. For example, l=range(13) would give the same result.

The result is a list of tuples. If your input is a string and you want to produce a list of strings, you can do

>>> l="Code_golf"
>>> map(''.join,zip(*[iter(l)]*3)) 
['Cod', 'e_g', 'olf'] # Python 3 would give a map object

When the list l is defined by a list comprehension, instead of converting to an iterable as iter(l), you can instead write it as a generator comprehension with (...) instead of [...].

>>> l=(n for n in range(18)if n%3!=1)
>>> zip(*[l]*4)
[(0, 2, 3, 5), (6, 8, 9, 11), (12, 14, 15, 17)]

This consumes the generator, so l will appear empty afterwards. Note as before that we can inline l as zip(*[(n for n in range(18)if n%3!=1)]*4).

  1. from lib import func as F

  2. from lib import*;F=func

  3. import lib;F=lib.func

#2 is better than #1 except in rare cases where something in lib clobbers another name that's important to you.

#3 uses lib twice, winning with short library names.

In Python,

True == 1   # true
False == 0  # true

So,

(a<b)*2-1

returns 1 if b is larger than a. If not, returns -1.

More golfing,

-(a>b)|1

returns exactly same value as mentioned above.

Useful when modify iterator index by comparable values.

Unpacking in Python3

If you only need the first few values in the array

>>> a, b, *c = [1, 2, 3, 4, 5]
>>> a
1
>>> b
2
>>> c
[3, 4, 5]

Same applies to when you need last few values

>>> *a, b, c = [1, 2, 3, 4, 5]
>>> a
[1, 2, 3]
>>> b
4
>>> c
5

Or even with the first few and last few

>>> a, *b, c = [1, 2, 3, 4, 5]
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

Slicing tricks for hard-wired lists of strings

Warning: Python is the language which worships readability above all else; so coding this way is a Mortal Sin.

This sort of thing comes up a lot; such as here where for a given digit in 0<=d<=9, we can get the 7-bit segment b value as a hex string from the list

b=['7e','30','6d','79','33','5b','5f','70','7f','7b'][d]

If the length of such a list is more than just a few elements, you're usually better off at least using split because you can replace a bunch of "','"s with a single character " " as delimiter. E.g.:

b='7e 30 6d 79 33 5b 5f 70 7f 7b'.split()[d]

This can be used for almost any list of strings (possibly at a small additional cost using a delimiter such as ",").

But if in addition, the strings we are selecting for all have the same length k (k==2 in our example), then with the magic of Python slicing, we can write the above as:

b='7e306d79335b5f707f7b'[2*d:][:2]

which saves a lot of bytes because we don't need character delimiters at all. But in that case, usually even shorter would be:

b='7367355777e0d93bf0fb'[d::10]

Formatting a Matrix

I've seen this code to get a character matrix (2D array) as a string.

'\n'.join(''.join(i)for i in M)

It's shorter to use a map instead:

'\n'.join(map(''.join,M))

If you're printing the result, it's shortest to use a for loop:

print('\n'.join(map(''.join,M)))
for i in M:print(*i,sep='')      # -5 bytes

If you're using Python 2, you can't use the print trick, but you can still use the for loop:

for i in M:print(''.join(i))     # -3 bytes

Binomial coefficient

The binomial coefficient \$\binom{n}{k} \ = \frac{n!}{k!(n-k)!}\$ can be expressed arithmetically as

((2**n+1)**n>>n*k)%2**n

Try it online!

This works for \$n,k \geq 0\$, except for \$n=k=0\$ it gives \$0\$ rather than \$1\$. More generally, it works to use

(b+1)**n/b**k%b

(TIO), where \$b\$ is any value strictly greater than the result. The first expression uses \$b=2^n\$, which exceeds \$\binom{n}{k}\$ except for \$n=k=0\$.


Why does this work? Let's look at an example with b=1000. Then, for n=6, we have

(b+1)**n = 1001 ** 6 = 1006015020015006001

Note how triples of digits encode the binomial coefficients in the n=6 row of Pascal's triangle:

1   6  15  20  15   6   1
1 006 015 020 015 006 001

This works because the binomial coefficients are the coefficients of the polynomial

$$ (b+1)^n = \sum_{k=0}^n\binom{n}{k}b^k$$

and so can be read off as digits in base b, as long no binomial coefficient exceeds b which would cause regrouping.

We can extract a given triple of digits, say for \$\binom{6}{2}=15\$, by floor-dividing by 1000000 to delete the last 6 digits leaving 1006015020015, then take %1000 to extract the last triplet 015. More generally, doing /b**k%b extracts the k-th digit from the end zero-indexed in base b, that is the digit with multiplier b**k.

Shorter way to copy/clone a list

(not deep clone. For deep clone see this answer)

(credit to this answer)

a=x[:]
b=[*x]
c=x*1

Try it online!

To assign to a tuple, don't use parentheses. For example, a=1,2,3 assigns a to the tuple (1, 2, 3). b=7, assigns b to the tuple (7,). This works in both Python 2 and Python 3.

Large hard coded numbers can be represented in larger bases, but there is a trade off. Higher bases only become worthwhile after a certain cutoff.

The only three bases you're likely to need to worry about are 10, 16, and 36. These are the cutoffs:

1000000000000 (13 bytes)                            -> 0xe8d4a51000 (12 bytes)
0x10000000000000000000000000000000000000 (40 bytes) -> int("9gmd8o3gbbaz3m2ydgtgwn9qo6xog",36) (39 bytes)

Choosing one of two numbers based on a condition

You already know to use the list selection [x,y][b] with a Boolean b for the ternary expression y if b else x. The variables x, y, and b can also be expressions, though note that both x and y are evaluated even when not selected.

Here's some potential optimizations when x and y are numbers.

You can also switch x and y if you can rewrite b to be its negation instead.

Negating Booleans

So you have a Boolean... a real Boolean, not one represented as an integer. You have a condition where it needs to be negated, and you can't just go back and negate it where you got it (e.g. != instead of ==), maybe because you use it once straight and once negated.

Well, who says your Booleans aren't longing to be integers deep in their little hearts?

>>> False < 1
True
>>> True < 1
False

8 bytes, not counting the colon:

if not C:

6 bytes:

if C<1:

EDIT: 5 bytes, thanks to user202729 in the comments:

if~-C:

This works because:

>>> -False
0
>>> -True
-1
>>> ~-False
-1
>>> ~-True
0

Use Splat (*) to pass a bunch of single character strings into a function

For example:

a.replace("a","b")
a.replace(*"ab")    -2 bytes

some_function("a","b","c")
some_function(*"abc")       -5 bytes

In fact, if you have n single-character strings, you will save 3(n - 1) - 1 or 3n - 4 bytes by doing this (because each time, you remove the "," for each one and add a constant *).

Difference of two parallel expressions

Say you have a challenge to find the difference of some characteristic on two inputs. Your solution has the form lambda a,b:e(b)-e(a), where e is some long expression you've written. Repeating e twice is wasteful, so what do you do?

Here are templates sorted by length. Assume that e stands for a long expression, not one that's already defined as a function. Also assume inputs can be taken in either order.

31 bytes*

lambda*l:eval('e(%s)-'*2%l+'0')

*Requires that e only mentions its variable once. Assumes -e(x) negates the whole expression, otherwise requires parens like -(e(x)) for two more bytes.

34 bytes

f=lambda a,*b:e(a)-(b>()and f(*b))

36 bytes

lambda a,b:d(b)-d(a)
d=lambda x:e(x)

36 bytes

a,b=[e(x)for x in input()]
print b-a

37 bytes

r=0
for x in input():r=e(x)-r
print r

39 bytes

lambda*l:int.__sub__(*[e(x)for x in l])

Fuse list comprehensions

You can write

[f(x)for x in l]+[g(x)for x in l]

As

sum([[f(x),g(x)]for x in l],[])

It gets even better with more comprehensions or if you have to take out more values

If you need to expand a list you can even turn l+[f(x)for x in l]+[g(x)for x in l] into sum([[f(x),g(x)]for x in l],l)

Common helper functions

These are some golfed implementations of number theoretic functions that come up in challenges a lot. Many of these are due to xnor, especially the “Wilson’s theorem prime machines” of the form lambda n,i=1,p=1. The coprime/totient functions are Dennis’s (explanation here).

It is instructive to study what exactly these are doing, so that you can adapt them to your needs or roll them into another recursive function. That often ends up being shorter than pasting these directly into your solution as-is!

All of these assume n is a positive integer. The ones marked with an asterisk produce the wrong result if n = 1. Furthermore, these snippets assume Python 2. For Python 3, you might need to replace / by // here and there.

# Function                                                   Output of f(360)
#========================================================================================
f=lambda n,i=2:n/i*[0]and[f(n,i+1),[i]+f(n/i)][n%i<1]      # [2, 2, 2, 3, 3, 5] (slow!)
f=lambda n,i=2:n/i*[0]and f(n,i+1)if n%i else[i]+f(n/i)    # [2, 2, 2, 3, 3, 5]
f=lambda n,i=2:n/i*[0]and(n%i and f(n,i+1)or[i]+f(n/i))    # [2, 2, 2, 3, 3, 5]
f=lambda n,i=2:n<2and{1}or n%i and f(n,i+1)or{i}|f(n/i)    # {1, 2, 3, 5}
f=lambda n,i=2:n<2and{i}or n%i and f(n,i+1)or{i}|f(n/i,i)  #*{2, 3, 5}
f=lambda n,i=2:n/i and[f(n,i+1),i+f(n/i)][n%i<1]           # 2+2+2+3+3+5 (slow!)
f=lambda n,i=2:n/i and f(n,i+1)if n%i else i+f(n/i)        # 2+2+2+3+3+5
f=lambda n,i=2:n/i and(n%i and f(n,i+1)or i+f(n/i))        # 2+2+2+3+3+5
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-p%i,i+1,p*i*i)     # first n primes
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-1,i+1,p*i*i)       # primes <= n
f=lambda n,i=1,p=1:n/i and p%i*i+f(n,i+1,p*i*i)            # sum of primes <= n
f=lambda n,i=1,p=1:n/i and p%i+f(n,i+1,p*i*i)              # count primes <= n
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)               # nth prime
f=lambda n:all(n%m for m in range(2,n))                    #*is n prime? (not recursive)
f=lambda n:1>>n or n*f(n-1)                                # factorial
f=lambda n:sum(k/n*k%n>n-2for k in range(n*n))             # totient phi(n) (not recursive)
f=lambda n:[k/n for k in range(n*n)if k/n*k%n==1]          # coprimes up to n (not recursive)

Try it online!

Additions and byte saves are very welcome!

Checking the length of a list

Empty      : `a==[]` but just checking if it's non empty and swapping the if and the else can be shorter 
Non-Empty  : `a` (assuming it is in a situation where it will be interpreted as a boolean)
len(a)>i   : `a>a[:i]` if the list is non-empty

Multiple statements can be put on one line separated by ;. This can save a lot of whitespace from indentation.

while foo(a):
 print a;a*=2

Or even better:

while foo(a):print a;a*=2

If you want to know the type of a variable x:

x*0is 0  # -> integer
x*0==0   # -> float (if the previous check fails)
x*0==""  # -> string
x*0==[]  # -> array

Use powers of the imaginary unit to calculate sines and cosines.

For example, given an angle d in degrees, you can calculate the sine and cosine as follows:

p=1j**(d/90.)
s=p.real
c=p.imag

This can also be used for related functions such as the side length of a unit n-gon:

l=abs(1-1j**(4./n))

If transforming from list to a tuple or set to a set, list or tuple is needed, as of Python 3.5 you can use the splat operator:

tuple(iterable) -> (*iterable,)  (-3 bytes)
set(iterable)   -> {*iterable}   (-2 bytes)
list(iterable)  -> [*iterable]   (-3 bytes)

If you're doing this as well as appending/prepending, you can do the following for an extra bonus:

iterable+[1]       -> *iterable,1          (-2 bytes, 3 for tuples)
iterable+iter2     -> *iterable,*iterable2 (+1 byte, 0 for tuples, though can combine types)
[1]+iterable+[1]   -> 1,*iterable,1        (-3 bytes, -4 for tuples)
iterable+[1]+iter2 -> *iterable,1,*iter2   (0 bytes, -1 for tuples)

Basically, ,* instead of , gives a +1 byte penalty and , instead of ,[] gives -2 bytes.

This shows [1,*iterable,1] is a golfier way of doing [1]+iterable+[1] by one byte, even when we're not doing any type conversion.

And just for fun, {*{}} is the same length as set() for challenges without letters.

Pathlib from shorter files manipulations:

# get current dir, go up one dir, go down one dir, list all "py" files
# and get the whole file bytes

import os.path as p
import glob

d = p.join(p.dirname(p.abspath(__file__))), 'foo', '*.py')
for x in glob.glob(d):
    with open(x, 'rb') as f:
        do_stuff(f)

Becomes:

import pathlib as p

d = p.Path(__file__).absolute().parent / 'foo'
for f in d.glob('*.py'):
    do_stuff(f.read_bytes())

Tricks with dicts:

# create a dict from iterable
d = {k: None for k in iterable}
# merge 2 dicts
d.merge(d1)
d.merge(d2)
# access a key, if it doesn't exist set a default value and return it
if 'foo' not in d:
    res = d['foo'] = 'bar'
    res = 'bar
else:
    res = d['foo']

Becomes:

d = {**dict.fromkeys(iterable), **d1, **d2}
res = d.setdefault('foo', 'bar')

Or if you need repeated access:

import collections as c
d = c.ChainMap(dict.fromkeys(iterable), d1, d2, {'foo': 'bar'})
res = d['foo']

Slicing can assign:

Converting BGR pixels array to RGB:

l = len(pixels)
for idx in range(0, l - 2, 3):
    pixels[idx + 2], pixels[idx] = pixels[idx], pixels[idx + 2]

Becomes:

l = len(pixels)
pixels[2:l:3], pixels[0:l:3] = pixels[0:l:3], pixels[2:l:3]

It's not just shorter. It's 5 times faster. Except on pypy, where the first version is 2x times faster :)

Format() works on dates:

"We are in year: %s" % (date.strftime('%y'))

Becomes:

"We are in year: {:%y}".format(date)

Or even better with f-strings:

f"We are in year: {date:%y}"

Rename everything

Here's a little Python 2 snippet that takes a module and a string, and renames every function in that module whose name is longer than 2 characters to a single character with the provided string prefixed. If you're writing a VERY LONG python program that uses many library or builtin functions (and if you manage to golf this snippet better than I have), it has the potential to save quite a few characters. On short programs or programs that use few functions, it will be useless. Since dir() sorts the names in a module, this will always provide the same names to the same functions, and you can use globals() to inspect which names it has given to which functions.

import string
def _(x,y):
 for c,f in zip(string.letters,[x.__dict__[q]for q in dir(x)if q in x.__dict__ and(len(q)>2)*type(x.__dict__[q]).__name__.find('eth')>0]):globals()[y+c]=f

You can use it to rename all the string and builtin functions like so:

_(str,'s')
_(__builtins__,'')

And then see what you actually ended up naming them like so:

for k in sorted(globals().keys(),key=lambda x:`len(x)`+x):print k,globals()[k]

If you only want to rename the builtin functions, it's best not to define the function and just use the body directly:

import string
b=__builtins__
for c,f in zip(string.letters,[b.__dict__[q]for q in dir(b)if(len(q)>2)*type(x.__dict__[q]).__name__.find('eth')>0]):globals()[c]=f

You can use the good old alien smiley face to reverse sequences:

[1, 2, 3, 4][::-1] # => [4, 3, 2, 1]

Access list, while building it inside comprehension

In python version 2.4 (and <2.3 with some tweaks) it is possible to access list, from list comprehension. Source #1, Source #2 (Safari, Python Cookbook, 2nd edition)

Python creates secret name _[1] for list, while it is created and store it in locals. Also names _[2], _[3]... are used for nested lists.

So to access list, you may use locals()['_[1]'].

In earlier versions this is not enough. You'll need to use locals()['_[1]'].__self__

I couldn't find evidence, that somethins like that is possible in versions >2.4

Don't think, that it might be usefull often, but who knows! At least it helps with building one-liners.

Example:

# Remove duplicates from a list:
>>> L = [1,2,2,3,3,3]
>>> [x for x in L if x not in locals()['_[1]']]
[1,2,3]

If you're drawing, for colors, instead of typing:

'#000' for black you can just use 0 (no apostrophes)
'#fff' for white you can simply use ~0 (no apostrophes)
'#f00' for red you can just use 'red'


Example of white being used with ~0

from PIL.ImageDraw import*
i=Image.new('RGB',(25,18),'#d72828')
Draw(i).rectangle((1,1,23,16),'#0048e0',~0)
i.show()

Easiest way to swap two values

>>> a=5
>>> b=4
>>> a,b=b,a
>>> a
4
>>> b
5

Store 8-bit numbers compactly as a bytes object in Python 3

In Python 3, a bytes object is written as a string literal preceded by a b, like b"golf". It acts much like a tuple of the ord values of its characters.

>>> l=b"golf"
>>> list(l)
[103, 111, 108, 102]
>>> l[2]
108
>>> 108 in l
True
>>> max(l)
111
>>> for x in l:print(x)
103
111
108
102

Python 2 also has bytes objects but they act as strings, so this only works in Python 3.

This gives a shorter way to express an explicit list of numbers between 0 to 255. Use this to hardcode data. It uses one byte per number, plus three bytes overhead for b"". For example, the list of the first 9 primes [2,3,5,7,11,13,17,19,23] compresses to 14 bytes rather than 24. (An extra byte is used for a workaround explained below for character 13.)

In many cases, your bytes object will contain non-printable characters such as b"\x01x02\x03" for [1, 2, 3]. These are written with hex escape characters, but you may use them a single characters in your code (unless the challenge says otherwise) even though SE will not display them. But, characters like the carriage return b"\x0D" will break your code, so you need to use the two-char escape sequence "\r".

A condition like

s = ''
if c:
    s = 'a'

can be written as

s = c*'a'

and there is possibly a need for parenthesis for condition.

This can also be combined with other conditions as (multiple ifs)

s = c1*'a' + c2*'b'

or (multiple elifs)

s = c1*'a' or c2*'b'

For example FizzBuzz problem's solution will be

for i in range(n):
    print((i%3<1)*"Fizz"+(i%5<1)*"Buzz" or i)

When mapping a function on a list in Python 3, instead of doing [f(x)for x in l] or list(map(f,l)), do [*map(f,l)].

It works for all other functions returning generators too (like filter).

The best solution is still switching to Python 2 though

Booleans are integers, too!

assert True == 1
assert False == 0
assert 2 * True == 2
assert 3 * False == 0
assert (2>1)+(1<2) == 2

If you have a statement like [a,a+x][c] (where c is some boolean expression), you can do a+x*c instead and save a few bytes. Doing arithmetic with booleans can save you lots of bytes!

Use IDLE 3.3 to take multiline input

In IDLE versions 3.1 to 3.3, the command input() reads an entire multiline string like "line1\nline2", rather than a single line at a time as per the spec. This was fixed in version 3.4.

Calling input() only once is very convenient for golfing. Whether one can take advantage of this is debatable, but I think it is an acceptable interpreter- or environment-specific behavior.

Use .center in ASCII art

In drawing a symmetrical ASCII art, you can center-justify each line in a fixed width of spaces. For example, "<|>".center(7) gives ' <|> '. This can be shorter than computing how many spaces are needed to center it.

You can also pad with a different character by doing "<|>".center(7,'_')

Use f-strings

Python 3.6 introduces a new string literal that is vastly more byte-efficient at variable interpolation than using % or .format() in non-trivial cases. For example, you can write:

l='Python';b=40;print(f'{l}, {b} bytes')

instead of

l='Python';b=43;print('%s, %d bytes'%(l,b))

Find the n'th number meeting a condition

Many sequence challenges ask you to find the n'th number in a sequence of increasing positive integers. When you have a expression p(i) that checks membership, you can do this with the recursive function:

f=lambda n,i=1:n and-~f(n-p(i),i+1)

Note that expression p(i) must give 0 or 1, not just Falsey or Truthy. The outputs are one-indexed, so say for the sequence of primes, it would give

f(1) = 2
f(2) = 3
...

For 0-indexed outputs, shift the base case

f=lambda n,i=1:n+1and-~f(n-p(i),i+1)

The recursive function f=lambda n,i=1:n and-~f(n-p(i),i+1) works by decrementing the required count n each time it gets a hit, and incrementing the output value each time for each value it checks. It might seem weird to redundantly track i, but it's longer to do:

f=lambda n,i=1:n and f(n-p(i),i+1)or~-i

Also compare the natural list strategy (zero-indexed here)

lambda n:[i for i in range(n*n)if p(i)][n]

(You might need a larger bound than n*n.)

Omit needless spaces

Python tokens only need to separated by a space for

In all other cases, the space can be omitted (with a few exceptions). Here's a table.

  L D S
 +-----
L|s s n
D|n - n
S|n n n    

First token is row, second token is column
L: Letter
D: Digit
S: Symbol

s: space
n: no space
-: never happens (except multidigit numbers)

Examples

Letter followed by letter: Space

not b
for x in l:
lambda x:
def f(s):
x in b"abc"

Letter followed by digit: Space

x or 3
while 2<x:

Letter followed by symbol: No space

c<d
if~x:
x and-y
lambda(a,b):
print"yes"
return[x,y,z]

Digit followed by letter: No space

x+1if x>=0else 2
0in l

(Some versions of Python 2 will fail on a digit followed by else or or.)

Digit followed by digit: Never occurs

Consecutive digits make a multidigit number. I am not aware of any situation where two digits would be separated by a space.

Digit followed by symbol: No space

3<x
12+n
l=0,1,2

A space is needed for 1 .__add__ and other built-ins of integers, since otherwise the 1. is parsed as a float.

Symbol followed by letter: No space

~m
2876<<x&1
"()"in s

Symbol followed by digit: No space

-1
x!=2

Symbol followed by symbol: No space

x*(a+b)%~-y
t**=.5
{1:2,3:4}.get()
"% 10s"%"|"

map can take multiple iterable arguments and apply the function in parallel.

Instead of

a=[1,4,2,6,4]
b=[2,3,1,8,2]
map(lambda x,y:...,zip(a,b))

you can write

map(lambda x,y:...,a,b)

Ceil and Floor

If you ever want to get the rounded-up result for a division, much like you'd do with // for floor, you could use math.ceil(3/2) for 15 or the much shorter -(-3//2) for 8 bytes.

math.floor(n)   : 13 bytes+12 for import
n//1            : 4  bytes

math.ceil(n)    : 12 bytes+12 for import
-(-n//1)        : 8  bytes

One trick I have encountered concerns returning or printing Yes/No answers:

 print 'YNeos'[x::2]

x is the condition and can take value 0 or 1.

I found this rather brilliant.

Abuse of or in lambdas

I'm surprised this isn't in here yet, but if you need a multi-statement lambda, or evaluates both of its operands, as opposed to and which doesn't evaluate the second one if the first one is not True. For instance, a contrived example, to print the characters in a string one by one with an interval:

list(
    map(
        (lambda i: 
            sleep(.06) or print(i) or print(ord(i)) # all of these get executed
        ), 
        "compiling... "
    )
)
            

In this case it isn't shorter, but I've found it to be, sometimes.

cmp in Python 2

Say you want to output P if x>0, N if x<0, and Z if x==0.

"ZPN"[cmp(x,0)]

Try it online

This function was removed in Python 3.0.1, although it remained in Python 3.0 by mistake.

Use slicing + assignment instead of mutator methods

l.insert(x,y) # before
l[x:x]=y,     # after

l.reverse()   # before
l[::-1]=l     # after

l.append(x)   # before
l[L:]=x,      # after (where L is any integer >= len(l))

l[:]=x        # set the contents of l to the contents of x

EDIT: thanks to @quintopia for pointing this out, these are statements, not expressions. The mutator methods are void functions, so they are expressions which evaluate to None. This means that things like [l.reverse() for x in L] and condition or l.reverse() are valid, whereas [l[::-1]=l for x in L] and condition or l[::-1]=l are not.

Use complex numbers to find the distance between two points

Say you have two 2-element tuples which represent points in the Euclidean plane, e.g. x=(0, 0) and y=(3, 4), and you want to find the distance between them. The naïve way to do this is

d=((x[0]-y[0])**2+(x[1]-y[1])**2)**.5

Using complex numbers, this becomes:

c=complex;d=abs(c(*x)-c(*y))

If you have access to each coordinate individually, say a=0, b=0, c=3, d=4, then

abs(a-c+(b-d)*1j)

can be used instead.

Optional empty sequence argument

Suppose we want to write a recursive function that prepends to a sequence (e.g. list, tuple) each time. For example, the Python 3 program

def f(n,k,L=[]):n and[f(n-1,k,[b]+L)for b in range(k)]or print(L)

works like itertools.product, taking n,k and printing all length n lists of numbers taken from range(k). (Example thanks to @xnor)

If we don't need L to be a list specifically, we can save on the optional empty list argument by making use of unpacking, like so:

def f(n,k,*T):n and[f(n-1,k,b,*T)for b in range(k)]or print(T)

where T is now a tuple instead. In the general case, this saves 3 bytes!

In Python 3.5+, this also works if we're appending to the end of a sequence, i.e. we can change f(n-1,k,L+[b]) to f(n-1,k,*T,b). The latter is a syntax error in earlier versions of Python though.

Take multi-line input

Use list(iter(input,eof)) to take multi-line input. eof can be any string that you want to stop taking input on if you see it. An example would be eof = ''. The python 2 version is list(iter(raw_input,eof)), however you may want to use sys.stdin.readlines() instead if you have already imported sys.

>>> for i in range(x):s+=input()

if value of i is useless:

>>> for i in[0]*x:s+=input()

or

>>> exec's+=input();'*x

Reading multi-line input

In Python 3, the built-in function open underwent some changes. In particular, its first argument

file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

(source)

That means

open(0).read()

suffices to read all input from STDIN.

Try it online on Ideone.

You can assign to a list inside of a for loop.

For example:

L=[1, 2, 3, 4, 6]
queue = [None]*len(L)
for e, queue[e] in enumerate(L):
    print("adding", queue[e], "to processing queue")

This can also be helpful if you need to switch the object you're assigning to.

class Foo:
    def __init__(self):
        self.x = None
a = Foo()
b = Foo()
for q, (lambda x: a if x%2==0 else b)(q).x in enumerate(range(10)):
    print(a.x, b.x)

For integer n, you can write

because the bit flip ~x equals -1-x. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence.

Compare:

while n-1:  #Same as while n!=1 
while~-n:

c/(n-1)
c/~-n

or f(n)+1
or-~f(n) 

(n-1)/10+(n-1)%10
~-n/10+~-n%10

The operators ~ and unary - are higher precedence than *, /, %, unlike binary +.

Exploit Python 2 string representations

Python 2 lets you convert an object x to its string representation `x` at a cost of only 2 chars. Use this for tasks that are easier done on the object's string than the object itself.

Join characters

Given a list of characters l=['a','b','c'], one can produce ''.join(l) as `l`[2::5], which saves a byte.

The reason is that `l` is "['a', 'b', 'c']" (with spaces), so one can extract the letters with a list slice, starting that the second zero-indexed character a, and taking every fifth character from there. This doesn't work to join multi-character strings or escape characters represented like '\n'.

Concatenate digits

Similarly, given a non-empty list of digits like l=[0,3,5], one can concatenate them into a string '035' as `l`[1::3].

This saves doing something like map(str,l). Note that they must be single digits, and can't have floats like 1.0 mixed in. Also, this fails on the empty list, producing ].

Check for negatives

Now, for a non-string task. Suppose you have a list l of real numbers and want to test if it contains any negative numbers, producing a Boolean.

You can do

'-'in`l`

which checks for a negative sign in the string rep. This shorter than either of

any(x<0for x in l)
min(l+[0])<0   

For the second, min(l)<0 would fail on the empty list, so you have to hedge.

Use a list if you have multiple choices based on int

Say for example you have some output that will be 1, 0, or -1 and you need a different output for each case. You could do something like this:

print('0'if x==0else('1'if x>0else'-1'))

However, the better way is to use x as an index to a list like so:

print(['0','1','-1'][x])

which is 16 bytes shorter.

Convert modules to lists

This will work for CPython (probably both 2 and 3), and lets you maybe shave a few bytes if you need to use a lot of different functions and classes with long names from the same module, but you aren't using any of them often enough to rename individually. You'll have to do some research first to figure out which magic numbers give you which functions. Example (rot13):

d=sorted
e=".__dict__.values()"
b=d(eval("__builtins__"+e))
s=d(eval("str"+e))
t=b[12]('string').maketrans
r=''.join(map(chr,range(65,91)))
w=r[13:]+r[:13]
l=t(r+s[4](r),w+s[4](w))
print s[28](b[53](),l)

Translated back to plain python, this is the same as:

t=__import__('string').maketrans
r=''.join(map(chr,range(65,91)))
w=r[13:]+r[:13]
l=t(r+r.lower(),w+w.lower())
print raw_input().translate(l)

which is obviously much shorter, but it should be clear how this methodology would eventually save bytes on much longer, more complicated programs that use more modules.

Printing a string without a trailing newline in Python 3

Suppose you have a string s, and need to print it without a trailing newline. The canonical way of doing this would be

print(s,end='')

However, if we look at the documentation for print, we can see that print takes in a variable number of objects as its first parameter, with "variable number" including zero. This means that we can do

print(end=s)

instead, for a saving of 3 bytes.

Note that this only works when s is a string, since otherwise the conversion to string would be too expensive:

print(1,end='')
print(end=str(1))

Thanks to @Reticality for this tip.

Dictionary defaults as entries

Say you have an dictionary literal, which I'll denote {...}, and you want to get the value for a key k, with a default of d if k is missing.

You can save two bytes by prepending an entry rather than using get

{k:d,...}[k]
{...}.get(k,d)

Because later entries override earlier ones of the same key, the entry k:d gets overwritten if it appears in the dict, but remains if key k isn't present.

Note that this required writing k twice, which is fine for a variable, but poor when k is an expression.

Try a lambda expression

By default, submissions may be functions and functions may be anonymous. A lambda expression is often the shortest framework for input/output. Compare:

lambda s:s+s[::-1]
def f(s):return s+s[::-1]
s=input();print s+s[::-1]

(These concatenate a string with its reverse.)

The big limitation is that the body of a lambda must be a single expression, and so cannot contain assignments. For built-ins, you can do assignments like e=enumerate outside the function body or as an optional argument.

This doesn't work for expressions in terms of the inputs. But, note that using a lambda might still be worth repeating a long expression.

lambda s:s.lower()+s.lower()[::-1]
def f(s):t=s.lower();return t+t[::-1]

The lambda is shorter even though we save a char in the named function by having it print rather than return. The break-even point for two uses is length 12.

However, if you have many assignments or complex structures like loops (that are hard to make recursive calls), you're probably be better off taking the hit and write a named function or program.

PEP448 – Additional Unpacking Generalizations

With the release of Python 3.5, manipulation of lists, tuples, sets and dicts just got golfier.

Turning an iterable into a set/list

Compare the pairs:

set(T)
{*T}

list(T)
[*T]

tuple(T)
(*T,)

Much shorter! Note, however, that if you just want to convert something to a list and assign it to a variable, normal extended iterable unpacking is shorter:

L=[*T]
*L,=T

A similar syntax works for tuples:

T=*L,

which is like extended iterable unpacking, but with the asterisk and comma on the other side.

Joining lists/tuples

Unpacking is slightly shorter than concatenation if you need to append a list/tuple to both sides:

[1]+T+[2]
[1,*T,2]

(1,)+T+(2,)
(1,*T,2)

Printing the contents of multiple lists

This isn't limited to print, but it's definitely where most of the mileage will come from. PEP448 now allows for multiple unpacking, like so:

>>> T = (1, 2, 3)
>>> L = [4, 5, 6]
>>> print(*T,*L)
1 2 3 4 5 6

Updating multiple dictionary items

This probably won't happen very often, but the syntax can be used to save on updating dictionaries if you're updating at least three items:

d[0]=1;d[1]=3;d[2]=5
d={**d,0:1,1:3,2:5}

This basically negates any need for dict.update.

Avoid the repeat argument of itertools.product

As @T.Verron points out, in most cases (e.g. ranges and lists), you can instead do

product(*[x]*n)

However, even if you have a generator which you can only use once, like a Python 3 map, the repeat argument is still unnecessary. In such a case you can use itertools.tee:

product(x,repeat=n)
product(*tee(x,n))

For n = 2 you don't even need to include n, since 2 is the default argument to tee.

Translating chars in a string

I've seen this situation pop up a few times, so I thought a tip would be good.

Suppose you have a string s and you want to translate some chars of s to other chars (think ROT-13 like ciphers). For a more concrete example, suppose we want to swap just the as and bs in a string, e.g.

"abacus" -> "babcus"

The naïve way to do this would be:

lambda s:s.replace('a','T').replace('b','a').replace('T','b')

Note how we need to introduce a temporary 'T' to get the swapping right.

With eval, we can shorten this a bit:

lambda s:eval("s"+".replace('%s','%s')"*3%tuple("aTbaTb"))

For this particular example, iterating char-by-char gives a slightly better solution (feel free to try it!). But even so, the winner is str.translate, which takes a dictionary of from: to code points:

# Note: 97 is 'a' and 98 is 'b'
lambda s:s.translate({97:98,98:97})

In Python 2 this only works for Unicode strings, so unfortunately the code here is slightly longer:

lambda s:(u''+s).translate({97:98,98:97})

Some important points which make str.translate so useful are:

Make a mutable matrix

If you want to make a 3*4 grid of zeroes, the natural expression M=[[0]*4]*3 gives an unpleasant surprise if you modify an entry:

>>> M=[[0]*4]*3
>>> M
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> M[0][0]=1
>>> M
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

Since each row is a copy of the same list by reference, modifying one row modifies all of them, which is usually not the behavior you want.

In Python 2, avoid this with the hack (19 chars):

M=eval(`[[0]*4]*3`)

Doing eval(`_`) converts to the string representation, then re-evaluates it, converting the object to the code of how it's displayed. In effect, it's doing copy.deepcopy.

If you're OK getting a tuple of lists, you can do (18 chars):

M=eval('[0]*4,'*3)

to get ([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]). This lets you do M[0][0]=1 but not M[0]=[1,2,3,4]. It also works in Python 3.

Instead of range(x), you can use the * operator on a list of anything, if you don't actually need to use the value of i:

for i in[1]*8:pass

as opposed to

for i in range(8):pass

If you need to do this more than twice, you could assign any iterable to a variable, and multiply that variable by the range you want:

r=1,
for i in r*8:pass
for i in r*1000:pass

Note: this is often longer than exec"pass;"*8, so this trick should only be used when that isn't an option.

set literals in Python2.7

You can write sets like this S={1,2,3} This also means you can check for membership using {e}&S instead of e in S which saves one character.

Shorter isinstance

Instead of

isinstance(x,C) # 15 bytes

there are several alternatives:

x.__class__==C  # 14 bytes
'a'in dir(x)    # 12 bytes, if the class has a distinguishing attribute 'a'
type(x)==C      # 10 bytes, doesn't work with old-style classes
'K'in`x`        # 8 bytes, only in python 2, if no other classes contain 'K'
                # watch out for false positives from the hex address

Some of them may save extra bytes depending on the context, because you can eliminate a space before or after the expression.

Thanks Sp3000 for contributing a couple of tips.

A nice way to convert an iterable to list on Python 3:

imagine you have some iterable, like

i = (1,2,3,4)
i = range(4)
i = (x**2 for x in range(5))

But you need a list:

x=list(i)  #the default way
*x,=i      #using starred assignment -> 4 char fewer

It's very useful to make a list of chars out of a string

s=['a','b','c','d','e']
s=list('abcde')
*s,='abcde'

Alternatives to builtin string functions

str.capitalize for single words

Use str.title instead for single words. The difference between the two functions is that capitalize only capitalises the first word, while title capitalises all words:

>>> "the quick brown fox".capitalize()
'The quick brown fox'
>>> "the quick brown fox".title()
'The Quick Brown Fox'

str.index

str.find is almost always better, and even returns -1 if the substring is not present rather than throwing an exception.

str.startswith

See this tip by @xnor.

str.splitlines

str.split is shorter:

s.splitlines()
s.split('\n')

However, str.splitlines may be useful if you need to preserve trailing newlines, which can be done by passing 1 as the keepends argument.

Avoid list.insert

Instead of list.insert, appending to a slice is shorter:

L.insert(i,x)
L[:i]+=x,

For example:

>>> L = [1, 2, 3, 4]
>>> L[:-2]+=5,
>>> L
[1, 2, 5, 3, 4]
>>> L[:0]+=6,
>>> L
[6, 1, 2, 5, 3, 4]

When squaring single letter variables, it is shorter to times it by itself

>>> x=30
>>> x*x
900

Is one byte shorter than

>>> x=30
>>> x**2
900

Leak variables to save on assignment

Combining with this tip, suppose you have a situation like

for _ in[0]*x:doSomething()
a="blah"

You can instead do:

for a in["blah"]*x:doSomething()

to skip out on a variable assignment. However, be aware that

exec"doSomething();"*x;a="blah"

in Python 2 is just shorter, so this only really saves in cases like assigning a char (via "c"*x) or in Python 3.

However, where things get fun is with Python 2 list comprehensions, where this idea still works due to a quirk with list comprehension scope:

[doSomething()for a in["blah"]*x]

(Credits to @xnor for expanding the former, and @Lembik for teaching me about the latter)

None arguments in Python builtins

map (Python 2 only)

Mapping with None in place of a function assumes the identity function instead. This allows it to be used as an alternative to itertools.izip_longest for zipping lists to the length of the longest list:

>>> L = [[1, 2], [3, 4, 5, 6], [7]]
>>> map(None,*L)
[(1, 3, 7), (2, 4, None), (None, 5, None), (None, 6, None)]

For visualisation (with . representing None):

1 2                1 3 7
3 4 5 6      ->    2 4 .
7                  . 5 .
                   . 6 .

filter

filter with None also assumes the identity function, thus removing falsy elements.

>>> L = ["", 1, 0, [5], [], None, (), (4, 2)]
>>> filter(None, L)
[1, [5], (4, 2)]

This is a bit better than a list comprehension:

filter(None,L)
[x for x in L if x]

However, as @KSab notes, if all elements are of the same type then there may be shorter alternatives, e.g. filter(str,L) if all elements are strings.

Safely get the first element

You can check if a possibly-empty list l starts with a value x by doing

l[:1]==[x]

This gives False on an empty list, while l[0]==x gives an out-of-bounds error. Strings works similarly

s[:1]=='a'

In general, you can safely check the n'th element as

l[n:n+1]==[a]

or as l[n:][:1]==[a] when n is a long expression.

Avoid startswith

The string method startswith is too long. There are shorter ways to check if a string s starts with a prefix t of unknown length.

t<=s<t+'~'     #Requires a char bigger than any in s,t
s.find(t)==0
s[:len(t)]==t    
s.startswith(t)

The second one is well-suited for the truth/falsity of the negation.

if s.find(t):

Replace a value in a list

To replace every entry of value a with b in a list L, use:

map({a:b}.get,L,L)

For example,

L=[1,2,3,1,2,3]
a=2
b=3
print map({a:b}.get,L,L)

[1, 3, 3, 1, 3, 3]  #Output

In Python 3, this returns a map object rather than a list. The list entries can be any hashable values (ints, floats, strings, tuples, etc).

Here's how this works. A dictionary's get method takes a key and default value, and returns the dictionary's entry for that key, using the default value is the key is not present. This method is mapped method over each entry in L both as the key and the default value, which results in

[{a:b}.get(x,x) for x in L]

If x is a, then the dictionary transforms it to b, and otherwise, it defaults to itself. You can perform multiple replacements at the same time using a larger dictionary.

Credit to twobit on Anarchy Golf for exposing me to this trick.

String keys to dicts

For a dictionary with string keys which also happen to be valid Python variable names, you can get a saving if there's at least three items by using dict's keyword arguments:

{'a':1,'e':4,'i':9}
dict(a=1,e=4,i=9)

The more string keys you have, the more quote characters you'll save, so this is particularly beneficial for large dictionaries (e.g. for a kolmogorov challenge).

Not read all the answers but you can instead of

if x==3:
    print "yes"
else:
    print "no"

use

print "yes" if x==3 else "no"

Use eval to iterate

Say you want to apply f composed k times to the number 1, then print the result.

This can be done via an exec loop,

n=1
exec("n=f(n);"*k)
print(n)

which runs code like n=1;n=f(n);n=f(n);n=f(n);n=f(n);n=f(n);print(n).

But, it's one character shorter to use eval

print(eval("f("*k+'1'+")"*k))

which evaluates code like f(f(f(f(f(1))))) and prints the result.

This does not save chars in Python 2 though, where exec doesn't need parens but eval still does. It does still help though when f(n) is an expression in which n appears only once as the first or last character, letting you use only one string multiplication.

Build a string instead of joining

To concatenate strings or characters, it can be shorter to repeatedly append to the empty string than to join.

23 chars

s=""
for x in l:s+=f(x)

25 chars

s="".join(f(x)for x in l)

Assume here that f(x) stands for some expression in x, so you can't just map.

But, the join may be shorter if the result doesn't need saving to a variable or if the for takes newlines or indentation.

When using Python 3, for your final print statement, use exit to save one char (note: this prints to STDERR, so you might not be able to use this):

print('x')
exit('x')

exit even adds a trailing newline. There is one caveat, however: exit(some_integer) will not print.

If you're using a built-in function repeatedly, it might be more space-efficient to give it a new name, if using different arguments:

r=range
for x in r(10):
 for y in r(100):print x,y

Extended iterable unpacking ("Starred assignment", Python 3 only)

The best way to explain this is via an example:

>>> a,*b,c=range(5)
>>> a
0
>>> b
[1, 2, 3]
>>> c
4

We've already seen a use for this — turning an iterable into a list in Python 3:

a=list(range(10))
*a,=range(10)

Here are a few more uses.

Getting the last element from a list

a=L[-1]
*_,a=L

In some situations, this can also be used for getting the first element to save on parens:

a=(L+[1])[0]
a,*_=L+[1]

Assigning an empty list and other variables

a=1;b=2;c=[]
a,b,*c=1,2

Removing the first or last element of a non-empty list

_,*L=L
*L,_=L

These are shorter than the alternatives L=L[1:] and L.pop(). The result can also be saved to a different list.

Tips courtesy of @grc

Store lookup tables as magic numbers

Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an n.

0: False
1: True
2: False
3: False
4: False
5: False
6: False
7: True
8: False
9: True
10:True
11:True
12:False

Then, you can implement this lookup table concisely as:

3714>>i&1

with the resulting 0 or 1 being equal to False to True.

The idea is that the magic number stores the table as a bitstring bin(3714) = 0b111010000010, with the n-th digit (from the end) corresponding the the nth table entry. We access the nth entry by bitshifting the number n spaces to the right and taking the last digit by &1.

This storage method is very efficient. Compare to the alternatives

n in[1,7,9,10,11]
'0111010000010'[n]>'0'

You can have your lookup table store multibit entries that can be extracted like

 340954054>>4*n&15

to extract the relevant four-bit block.

Use ~ to index from the back of a list

If L is a list, use L[~i] to get the i'th element from the back.

This is the i'th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i].

Use extended slicing to select one string from many

>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz

vs

>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz

In this Boolean two-string case, one can also write

b*"string"or"other_string"

for

["other_string","string"][b]

Unlike interleaving, this works for strings of any length, but can have operator precedence issues if b is instead an expression.

Adding vectors

Python doesn't have a built-in way to do vector (component-wise) addition except with libraries. Say a and b are two equal-length lists of numbers you want to add. Instead of the list comprehension

c=[a[i]+b[i]for i in range(len(a))]

you can use

c=map(sum,zip(a,b))

This produces an annoying map object in Python 3, but it's shorter even if you have to convert to a list.

A great thing I did once is:

if 3 > a > 1 < b < 5: foo()

instead of:

if a > 1 and b > 1 and 3 > a and 5 > b: foo()

Python’s comparison operators rock.


Using that everything is comparable in Python 2, you can also avoid the and operator this way. For example, if a, b, c and d are integers,

if a<b and c>d:foo()

can be shortened by one character to:

if a<b<[]>c>d:foo()

This uses that every list is larger than any integer.

If c and d are lists, this gets even better:

if a<b<c>d:foo()

Iterating over indices in a list

Sometimes, you need to iterate over the indices of a list l in order to do something for each element that depends on its index. The obvious way is a clunky expression:

# 38 chars
for i in range(len(l)):DoStuff(i,l[i])

The Pythonic solution is to use enumerate:

# 36 chars
for i,x in enumerate(l):DoStuff(i,x)

But that nine-letter method is just too long for golfing.

Instead, just manually track the index yourself while iterating over the list.

# 32 chars
i=0
for x in l:DoStuff(i,x);i+=1

Here's some alternatives that are longer but might be situationally better

# 36 chars
# Consumes list
i=0
while l:DoStuff(i,l.pop(0));i+=1

# 36 chars
i=0
while l[i:]:DoStuff(i,l[i]);i+=1

If you are doing something small in a for loop whose only purpose is to invoke a side effect (pop, print in Python 3, append), it might be possible to translate it to a list-comprehension. For example, from Keith Randall's answer here, in the middle of a function, hence the indent:

  if d>list('XXXXXXXXX'):
   for z in D:d.pop()
   c=['X']

Can be converted to:

  if d>list('XXXXXXXXX'):
   [d.pop()for z in D]
   c=['X']

Which then allows this golf:

  if d>list('XXXXXXXXX'):[d.pop()for z in D];c=['X']

An if within a for works just as well:

for i in range(10):
 if is_prime(i):d.pop()

can be written as

[d.pop()for i in range(10)if is_prime(i)]

You can use default arguments of a function to save some indentation, since

def f(a,l=[1,2,3]):
 return sum(a==i for i in l)

is one byte shorter than

def f(a):
 l=[1,2,3]
 return sum(a==i for i in l)

Abusing try/except blocks can sometimes save characters, especially for exiting out of nested loops or list comprehensions. This:

for c in s:
 for i in l:
  q=ord(c)==i
  if q:print i,c;break
 if q:break

... can become this, saving 3 characters:

try:
 for c in s:
  for i in l:
   if ord(c)==i:print i,c;1/0
except:0

... which in this particular instance can be compressed even further using list comprehensions:

try:[1/(ord(c)-i)for c in s for i in l]
except:print i,c

For an example, see e.g. https://codegolf.stackexchange.com/a/36492/16766.

When your program needs to return a value, you might be able to use a yield, saving one character:

def a(b):yield b

However, to print it you'd need to do something like

for i in a(b):print i

To find the all the indexes of a certain element in a list l, use

filter(lambda x:l[x]==element,range(len(l)))

To find the next index after a certain index:

l[:index].index(element)

To find the nth index:

list(filter(lambda x:l[x]==element,range(len(l))))[n]

Cut out newlines wherever you can.

At the top-level, it doesn't matter.

a=1
b=9

Takes the same amount of characters as:

a=1;b=9

In the first case you have a newline instead of a ;. But in function bodies, you save however deep the nesting level is:

def f():
 a=1;b=9

Actually in this case, you can have them all on one line:

def f():a=1;b=9

If you have an if or a for, you can likewise have everything on one line:

if h:a=1;b=9
for g in(1,2):a=1;b=9

But if you have a nesting of control structures (e.g. if in a for, or if in a def), then you need the newline:

if h:for g in(1,2):a=1;b=9 #ERROR

if h:
 for g in(1,2):a=1;b=9 # SAUL GOODMAN

1 or 0 can act as boolean operators in Python:

func = lambda x:1 if x//2==x/2 else 0
while 1:
    if func(n):
         print('Hello')
    else:
         exit()

Which is 10 characters shorter than:

func = lambda x:True if x//2==x/2 else False
while True:
    if func(n):
         print('Hello')
    else:
         exit()

Use += instead of append and extend

A.append(B)  

can be shortened to:

A+=B,

B, here creates a one-element tuple which can be used to extend A just like [B] in A+=[B].


A.extend(B)

can be shortened to:

A+=B

If you rely on data (mostly for kolmogorov-complexity problems), use the built-in zip encoding/decoding and store the data in a file (add +1 for the filename):

open('f','rb').read().decode('zip')

If you have to store the data in the source code, then you need to encode the zip with base64 and do:

"base64literal".decode('base64').decode('zip')

These don't necessarily save characters in all instances, though.

You can generate pseudo random numbers using hash.

hash('V~')%10000

Will print 2014.

For ages it bothered me that I couldn't think of a short way to get the entire alphabet. If you use range enough that R=range is worth having in your program, then

[chr(i+97)for i in R(26)]

is shorter than the naive

'abcdefghijklmnopqrstuvwxyz'

, but otherwise it's longer by a single character. It haunted me that the clever one that required some knowledge of ascii values ended up being more verbose than just typing all the letters.

Until I saw this answer for My Daughter's Alphabet. I can't follow the edit history well enough to figure out if this genius was the work of the OP or if it was a suggestion by a commenter, but this is (I believe) the shortest way to create an iterable of the 26 letters in the Roman alphabet.

map(chr,range(97,123))

If case doesn't matter, you can strip off another character by using uppercase:

map(chr,range(65,91))

I use map way too much, I don't know how this never occurred to me.

Run your code through an space-remover, like this one:

#Pygolfer
a=raw_input()
for i in [i for i in range(len(a)) if a[i]==" "]:
    try:b=a[:i]+a[i+1:];eval(b);a=b;print a
    except:pass

(This just tries to remove the spaces one by one, and try if the code still works. Please still do check your code manually.)

Manual things to do: print'string' works.

[str(i)for i in(1,2,3,4)] works.

etc.

If you need to import a lot of modules you can reassign __import__ to something shorter, this also has the advantage of being able to name imports anything you want.

i=__import__;s=i('string');x=i('itertools');

When you have two boolean values, a and b, if you want to find out if both a and b are true, use * instead of and:

if a and b: #7 chars

vs

if a*b: #3 chars

if either value is false, it will evaluate as 0 in that statement, and an integer value is only true if it is nonzero.

If you represent boolean values as numbers you can save characters. This is especially true for using -1 as True.

Bitty conditionals work (Truth table):

a  b   &  |  ^ 
0  0   0  0  0
0  -1  0 -1 -1
-1 0   0 -1 -1
-1 -1 -1 -1  0

And ~ works as not:

 a ~a
 0 -1
-1  0

Even though the - for initializing -1 costs one character, this can easily save characters overall.

Compare:

while~a:

to:

while not a:

Sometimes you need convert boolean expression into integer (0/1) Simple use this Boolean (in examples below c > 0) in ariphmetic

a=b+(c>0)
a+=c>0
a=sum(c>0 for c in b) # space in "0 for" may be omitted

And sometimes you need simple convert boolean to int (for example for printing or convert to binary string). In programm you may use some variants

1 if c>0 else 0
c>0and 1or 0
(0,1)[c>0]
int(c>0)

but shortest way is

+(c>0)

If you have multidimensional array of numbers and for instance need to count all numbers greater than n.

First flatten the array, then apply filter function to match condition:

l=[[1,[8,4,7,1],3],[5,[7],3,9],[7,3,9,[[[8]]]]]
n=5
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
len(filter(lambda x:x>n,flatten(l)))

Change import * to import*


If you haven't heard, import* saves chars!

from math import*

is only 1 character longer than import math as m and you get to remove all instances of m.

Even one time use is a saver!

Be aware of all, any and map:

if isdigit(a) and isdigit(b) and isdigit(c)
if all(map(isdigit,[a,b,c]))

Lets play with some list tricks

a=[5,5,5,5,5,5,5]

can be written as:

a=[5]*7

It can be expanded in this way. Lets, say we need to do something like

for i in range(0,100,3):a[i]=5

Now using the slicing trick we can simply do:

a[0:100:3]=[5]*(1+99//3)

You only need to indent nested control structures:

def baz(i):
 if i==0:i=1;print i;bar()
 while i:i+=foo(i-1)

Was somewhat mentioned but I want to expand:

[a,b],[c,d]=[[1,2],[3,4]]

works as well as simple a,b=[1,2]. Another great thing is to use ternary operator (similiar to C-like ?:)

x if x<3 else y

and no one mentioned map. Map will call first function given as first argument on each item from second argument. For example assume that a is a list of strings of integers (from user input for example):

sum(map(int,a)) 

will make sum of all integers.

Abuse the fact that in case of an expression yielding True boolean operators return the first value that decides about the outcome of the expression instead of a boolean:

>>> False or 5
5

is pretty straightforward. For a more complex example:

>>> i = i or j and "a" or ""

i's value remains unchanged if it already had a value set, becomes "a" if j has a value or in any other case becomes an empty string (which can usually be omitted, as i most likely already was an empty string).

Just found out two new things. First, input() can parse tuples, like 1, 2, 3 is equivalent to the tuple (1, 2, 3).

And if you need to convert a value to float, just multiply by 1.. Yes, 1. is valid syntax (At least in 2.6).

use os.urandom() as a random source instead of random.randint()

loops up to 4 items may be better to supply a tuple instead of using range

for x in 0,1,2:

vs

for x in range(3):

Use extended slicing to select one of two strings

>>> for x in-2,2:print"WoolrlledH"[::x]
... 
Hello
World

vs

>>> for x in 0,1:print["Hello","World"][x]
... 
Hello
World

Sometimes you can use Python's exec-statement combined with string repetition, to shorten loops. Unfortunately, you can't often use this, but when you can you can get rid of a lot of long loop constructs. Additionally, because exec is a statement you can't use it in lambdas, but eval() might work (but eval() is quite restricted in what you can do with it) although it's 2 characters longer.

Here is an example of this technique in use: GCJ 2010 1B-A Codegolf Python Solution

If you're doing somewhat more complex golfing that require something from the standard library to be used a lot, import x as y can save some space:

import itertools as i
i.groupby(...) # same as itertools.groupby

Use os.read to read all input:

import os
s=os.read(0,1e9)

Which is shorter than

import sys
s=sys.stdin.read()

Note that this has a limitation on input length, but it's so ridiculously large I'd say we're safe from the angry mob.

Unless the following token starts with e or E. You can remove the space following a number.

For instance:

if i==4 and j==4:
    pass

Becomes:

if i==4and j==4:
    pass

Using this in complicated one line statements can save quite a few characters.

EDIT: as @marcog pointed out, 4or a will work, but not a or4 as this gets confused with a variable name.

A one line function can be done with lambda:

def c(a):
  if a < 3: return a+10
  else: return a-5

can be converted to (note missing space 3and and 10or)

c=lambda a:a<3and a+10or a-5