What is the most confusing thing to you in Python?
Florian Rohrer Sep 12, 2017
Just some traps and pitfalls that took me a while to get used to in Python.
List methods vs. built-in methods
# sort(), sorted(), reverse(), reversed() # sort() modifies the existing list and is a function of the list object # sorted() returns a new list and is a built-in function a = [5,2,8,1,9,3] sorted(a) # ok -> [1, 2, 3, 5, 8, 9] a.sort() # ok -> [1, 2, 3, 5, 8, 9] a.sorted() # ERROR # however, min() and max() are only built-in functions a.min() # ERROR min(a) # ok -> 1 # unless you work with numpy, where min() and max() do exist :S import numpy as np n = np.array([5,2,4,9,1,7]) n.min() # ok -> 1
# I have to call .join() on a string to concatenate a list = confusing. # concatenating a list of strings ", ".join(["apple", "banana", "cherry"]) # 'apple, banana, cherry' # even uglier, when list is not a string ", ".join([str(s) for s in [1,2,3,4]]) # '1, 2, 3, 4'
List of lists
# The wrong way a = [] * 5 # [, , , , ] a.append(1) # [, , , , ] # The right way a = [ for _ in range(5)]
'is' and '==' on ints
# Internally some int objects are cached. When you compare 2 ints, you should use ==. # However, using 'is' can also work in some cases. x = 2000 y = 2000 x is y # False -> good, because this should not be allowed anyways. x = 5 y = 5 x is y # True -> But this works.... # See also # https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers
Did you find any interesting or funny things in Python, that confused you the first time you saw them? Share them in the comments below.