a = [1, 2, 3]
b = a
b[1] = 4
print(a)
print(b)
[1, 4, 3] [1, 4, 3]
a = [1, 2, 3]
b = list(a)
b[1] = 4
print(a)
print(b)
[1, 2, 3] [1, 4, 3]
a = [1, [2, 3]]
b = list(a)
b[1][0] = 4
print(a)
print(b)
[1, [4, 3]] [1, [4, 3]]
import copy
a = [1, [2, 3]]
b = copy.copy(a)
b[1][0] = 4
print(a)
print(b)
[1, [4, 3]] [1, [4, 3]]
import copy
a = [1, [2, 3]]
b = copy.deepcopy(a)
b[1][0] = 4
print(a)
print(b)
[1, [2, 3]] [1, [4, 3]]
import math
def sample_function(t):
if t < -2:
return -2
elif -2 <= t < 0:
return t
elif t == 0:
return 0
else:
return t * math.sin(1 / t)
sample_function(-5)
-2
sample_function(-1)
-1
sample_function(0)
0
sample_function(1)
0.8414709848078965
%pylab inline
Populating the interactive namespace from numpy and matplotlib
t = arange(-5, 5, 0.01)
grid()
plot(t, list(map(sample_function, t)))
[<matplotlib.lines.Line2D at 0x10efddc50>]
x = 1 if True else 2
x
1
x = 1 if False else 2
x
2
a = [[1, 2], [3, 4]]
for x in a:
for y in x:
print(y)
1 2 3 4
for x, y in a:
print(x, y)
1 2 3 4
def f(a, b, c):
print(a, b, c, sep=", ")
f(1, 2, 3)
1, 2, 3
f(1, c=3, b=2)
1, 2, 3
a = [1, 2, 3]
f(a)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-6a4ba51a6ef9> in <module>() ----> 1 f(a) TypeError: f() missing 2 required positional arguments: 'b' and 'c'
f(*a)
1, 2, 3
a = [2, 3]
f(1, *a)
1, 2, 3
d = {'c': 3, 'b': 2, 'a': 1}
f(**d)
1, 2, 3
def f(a, b=2, c=3):
print(a, b, c, sep=", ")
f(1)
1, 2, 3
f(1, 4)
1, 4, 3
f(1, 4, 5)
1, 4, 5
def f(a, b=[]):
b.append(a)
print(b)
f(1)
[1]
f(2)
[1, 2]
f(3)
[1, 2, 3]
def f(*args, **kwargs):
print(args, kwargs, sep=", ")
f(1, 2, 3, x=4, y=5)
(1, 2, 3), {'y': 5, 'x': 4}
name = 'Alice'
"Hello, {0}".format(name)
'Hello, Alice'
"Hello, {}".format(name)
'Hello, Alice'
name1 = 'Bob'
name2 = 'Malory'
"Hello, {} and {}".format(name1, name2)
'Hello, Bob and Malory'
"{0}cad{0}".format("abra")
'abracadabra'
"{0.real} + {0.imag}i".format(1 + 2j)
'1.0 + 2.0i'
"Hello, {name}".format(name="Guido")
'Hello, Guido'
"Hello, {name[0]} and {name[1]}".format(name=["Jack", "Jill"])
'Hello, Jack and Jill'
a = 1
b = 2
"{a} + {b} = {}".format(a + b, **locals())
'1 + 2 = 3'