Pansop

Be Knowledgeable

A collection of pitfalls in Python. This is a part of Python Knowledge and Resources List

  1. Mutable data structures and assignment operator

    li1 = []

    li2=li1

    li2.append(1)

    print li1

    output : [1]


    This is because a single object is created and it is given several different names, so when you change the object, its reflected in all the variables which refer that object
  2. .sort(), .reverse() dont return a list

    li=[5,4,3,2,1]

    li2 = [-1,0]+li.sort()


    output: TypeError: can only concatenate list (not "NoneType") to list

    the list methods sort() and reverse() don't return the modified list


  3. When a variable is assigned inside a function python assumes its defined inside

    i=[1,2,3]

    def print_i():

        print i


    output: [1,2,3]


    def modify_i():

        i=i+[4,5]


    output: UnboundLocalError: local variable 'i' referenced before assignment


    <progress style="position: fixed; left: 0px; bottom: 0px; display: none; z-index: 99999;"></progress>
  4. Variable binding in closures

    def create_closures():

        return [lambda a: a*i for i in range(3)]


    for fun in create_closures():

        fun(1)


    output :

    2

    2

    2


    This is because the values of variables used in closures are looked up at the time inner function is called, so


    i=0

    def clarify_func():

        def clj(a):

            print a+i

        return clj

    i=2


    fun = clarify_func()

    fun(2)


    output : 4


Add a Resource to this List
Not more than 250 characters.