// * Python 2
my_list = [[0]*5]*4
for i in range(3):
my_list[2][i] = 1
print my_list
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
new_list = [[0]*5 for x in range(4)]
for i in range(3):
new_list[2][i] = 1
new_list
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 0, 0]]
Just don't. You would cry.
where, Tab(→) = 4 spaces
→ Some code here(firstArgument,
→ → → → ···secondOne,
→ → → ·······modified);
where, Tab(→)= 2 spaces
→ Some code here(firstArgument,
→ → → → ···secondOne,
→ → → ·······modified);
float('i-am-a-string')
float('inf')
float('inf') > 6
a={}
a[1.0]= 'quora'
a[True] = 'twitter'
a[1]= 'facebook'
print a[True]
hash(1) == hash(1.0)
a = 25
b = 25
print id(a)
print id(b)
a = 300
b = 300
print id(a)
print id(b)
This flaw bites people fairly often. Consider the following function; what do you think happens when you run it?:
i=1
def f():
#global i
print "i=",i
i = i + 1
f()
for i in range(10): print "*",
import sys
for i in range(10): sys.stdout.write("*")
try:
#something that raises an error...
except IndexError, ValueError:
# expects to catch IndexError and ValueError
# wrong!
# correct
try:
1/0
except (ZeroDivisionError, IndexError, ValueError), e:
print e
# integer division or modulo by zero
x += 42
x = x + 42
a = 1
a = a + 42
# a is 43
a = 1
a += 42
# a is 43
z = [1, 2, 3]
z += [4]
id(z)
z = z + [5]
id(z)
>>> class Foo:
... a = 42
... def __init__(self):
... self.a = 43
...
>>> f = Foo()
>>> f.a
43
>>> class Foo:
... a = 42
...
>>> f = Foo()
>>> f.a
42
class Foo:
bar = []
def __init__(self, x):
self.bar += [x]
# self.bar = self.bar + [x]
f = Foo(42)
f.bar
[42]
g = Foo(100)
g.bar
[42, 100]
>>> x = [10, 20, 30, 40, 50]
x = [10, 20, 30, 40, 50]
x[6:]
[]
>>> def myfunc(x=[]):
... x.append(222)
... print x
>>> myfunc([1, 2, 3])
[1, 2, 3, 222]
>>> x = [1, 2]
>>> myfunc(x)
[1, 2, 222]
>>> x
[1, 2, 222]
>>> myfunc()
[222]
>>> myfunc()
[222, 222]
>>> myfunc()
[222, 222, 222]
To illustrate this, a simple benchmark. (timeit is a simple function that runs another function and returns how long it took to complete, in seconds.)
>>> def f():
... s = ""
... for i in range(100000):
... s = s + "abcdefg"[i % 7]
...
>>> timeit(f)
23.7819999456
>>> def g():
... z = []
... for i in range(100000):
... z.append("abcdefg"[i % 7])
... return ''.join(z)
...
>>> timeit(g)
0.343000054359
>>> t = (1,2,[1,2,3],)
>>> t[2] += [4, 5]
t = (1,2,[1,2,3],)
t[2] += [4,5]
t
Don't :
if os.path.isfile(file_path) :
file = open(file_path)
else :
# do something
```
Do :
try :
file = open(file_path)
except OSError as e:
# do something