Алла Тамбовцева, НИУ ВШЭ
nums = [1, 8, 23, 45, 67]
nums_sq = []
for n in nums:
nums_sq.append(n ** 2)
print(nums_sq)
[1, 64, 529, 2025, 4489]
nums_sq = [n ** 2 for n in nums]
print(nums_sq)
[1, 64, 529, 2025, 4489]
%%timeit
R = []
for i in range(0, 5001):
R.append(i ** 3)
1.52 ms ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
R = [i ** 3 for i in range(0, 5001)]
1.35 ms ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
enumerate()
¶drinks = ['tea', 'coffee', 'juice', 'milk']
for d in drinks:
print(drinks.index(d), d) # метод index()
0 tea 1 coffee 2 juice 3 milk
for i in range(0, len(drinks)):
print(i, drinks[i])
0 tea 1 coffee 2 juice 3 milk
enumerate(drinks)
<enumerate at 0x10dc97a50>
list(enumerate(drinks)) # list of tuple
[(0, 'tea'), (1, 'coffee'), (2, 'juice'), (3, 'milk')]
for i, d in enumerate(drinks):
print(i, d)
0 tea 1 coffee 2 juice 3 milk