0

using for loop in single lines:

%%time
y = [x*2 if x%2 != 0 else x+2 for x in range(10000000)]


CPU times: user 1.27 s, sys: 150 ms, total: 1.42 s
Wall time: 1.42 s

using for loop in multiple lines:

%%time
y =[]
for x in range(10000000):
    if x%2 != 0:
        y.append(x*2)
    else:
        y.append(x+2)
CPU times: user 2.45 s, sys: 198 ms, total: 2.65 s
Wall time: 2.65 s

Why second for loop is taking more time? Both are doing the same thing.

Arayan Singh
  • 3,192
  • 3
  • 16
  • 35

1 Answers1

1

It's because appending to a list will cause this list to expand space many times. Reserve this required space at once will save expansion cost.

Try this:

y = [0] * 10000000
for x in range(10000000):
     if x % 2 != 0:
         y[x] = x*2
     else:
         y[x] = x+2
duyue
  • 759
  • 5
  • 12
  • have you compared your solution to others time-wise? note `if x % 2 != 0:` => `if x % 2:` – Jean-François Fabre Apr 13 '19 at 22:12
  • @Jean-FrançoisFabre this solution is slightly slower than the list comprehension one, but faster than the list append one. Open ipython and you can %%time them yourself. – duyue Apr 14 '19 at 07:46