14 things I didn’t know about python before I read the language reference

  1. You can attach an else clause to while and for loop, which will be executed once when the loop finishes normally. Do note that it will not be executed if you ‘break’ out of a loop.

   1 x=3

   2 while x>0:

   3     print “x is {}”.format(x)

   4     x-=1

   5 else:

   6     print “x is {}”.format(x)

   7

   8 for i in [1,2,3]:

   9     print “i is {}”.format(i)

  10 else:

  11     print “i is {}”.format(i)

output:

x is 3

x is 2

x is 1

x is 0

i is 1

i is 2

i is 3

i is 3

2. Multiple for syntax

print [x*y for x in range(10) for y in range(10)]

output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 0, 9, 18, 27, 36, 45, 54, 63, 72, 81]

3. In addition to using [a,b,c] to create an array, and {a:b, c:d} to create a dictionary. You can also use {a,b,c,d} syntax to create a set.

4.

  15 class simple:

  16     def __str__(self):

  17         return “str!”

  18

  19     def __repr__(self):

  20         return “repr!”

  21

  22 s = simple()

  23 print “string representation is “ + `s`

  24 print “error! “ + s

output:

string representation is repr!

Traceback (most recent call last):

  File “plr.py”, line 24, in <module>

    print “error! ” + s

TypeError: cannot concatenate ‘str’ and ‘instance’ objects

5. yield works like magic. It is particularly useful if, say, you use a recursive algorithm to find all possible permutations of a class. You don’t want to store all the results in an array, since it might be huge and time consuming. You can use ‘yield’ to calculate the next value on the go. So cool.

Except from the Python Language Reference.

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to generator’s caller. By suspended we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression was just another external call. The value of the yield expression after resuming depends on the method which resumed the execution.

6. You can specify a parameter to receive any additional parameter by adding a “*” before the name.

  26 def func(a,b,*c):

  27     print “{},{},{}”.format(a,b,c)

  28

  29 func(1,2)

  30 func(1,2,3)

  31 func(1,2,3,4,5)

output:

1,2,()

1,2,(3,)

1,2,(3, 4, 5)

Similarly, you can make a parameter to hole all additional formal parameters (parameter with names) by adding “**” before the name.

  33 def func(a,b,**c):

  34     print “{},{},{}”.format(a,b,c)

  35

  36 func(1,2)

  37 func(b=1,a=2)

  38 func(a=1,b=2,c=3)

  39 func(a=1,b=2,c=3,d=4)

output:

1,2,{}

2,1,{}

1,2,{‘c’: 3}

1,2,{‘c’: 3, ‘d’: 4}

7. You can chain a serious of operations together, each expression will be evaluated only once. the following code is the same as a<b and b<c and c==d

  41 a,b,c,d = 1,2,3,3

  42 if a<b<c==d:

  43     print “Yeah”

output:

Yeah

8. This features reminds me of ruby. It simplifies the process of setting default values.

  46 a,b = None,0

  47 a = a or 1

  48 b = b or 1

  49 print “{} {}”.format(a,b)

output:

1 1

9. nice simple if-else statement. Note that they do have to come in pair.

  51 a = False

  52 b = 1 if a else 0

  53 print b

output:

0

10. I did not know python supports assert, but now I know it does.

  55 assert False,“failed here”

output:

Traceback (most recent call last):

  File “plr.py”, line 55, in <module>

    assert False,”failed here”

AssertionError: failed here

11. You can add a comma after print to not add the newline character

  57 print “with new line”

  58 print “without new line”,

  59 print “see?”

output:

with new line

without new line see?

12. You can put a few statements after if statement, separated by semicolon. And they will behave just like what you would expect. However, you cannot put another if statement after the if, since a subsequent else will confuse the interpreter.

  61 a,b,c = 1,2,3

  62 if a<b<c:print a;print b;print c;

  63 #if a<b:if b<c:print b else print a; #not valid

output:

1

2

3

13. Finally always gets executed!

  65 def foo():

  66     try:

  67         return “A”

  68     finally:

  69         return “B”

  70

  71 print foo()

output:

B

14. Default parameter is evaluated the first time it is executed. It only create a single instance of the default value for all the instances it creates. This can be very dangerous.

  73 class foo:

  74     def __init__(self,list=[]):

  75         self.list = list

  76

  77 a,b = foo(),foo()

  78 print a.list

  79 a.list.append(1)

  80 print a.list

  81 print b.list

output:

[]

[1]

[1]

Comment:

I tested these features under Python 2.7.10. You should test it out to make sure it behaves the same way on your computer before using them!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s