0

In Python, the short form for building an array via a bracketized for loop is:

def get_row(runner):
    row = some_complicated_function()
    return row

my_array = [get_row(runner) for runner in range(10000)]

How would this look like if I want to avoid the condensed form of for loop?

  • 1
    _"How would this look like if I want to avoid the condensed form of for loop?"_ - `my_array = []; for runner in range(10000): my_array.append(get_row(runner))`. – Christian Dean Jun 09 '18 at 02:20
  • cool. thanks. And is this comparable with regards to performance/speed? –  Jun 09 '18 at 02:21
  • @user8042669 list-comprehensions tend to be faster since they [remove some overhead](https://stackoverflow.com/questions/30245397/why-is-a-list-comprehension-so-much-faster-than-appending-to-a-list) of accessing list.append. – Olivier Melançon Jun 09 '18 at 02:23
  • I'm not entirely sure @user8042669. I suspect the list comp would be faster. Why not try it out yourself :-) – Christian Dean Jun 09 '18 at 02:24

1 Answers1

1

The following code snippet (the one you provided is the list-comprehension)

my_array = [get_row(runner) for runner in range(10000)]

Here is an equivalent unrolled version

my_array = []
for runner in range(10000):
    row_runner = get_row(runner)
    my_array.append(row_runner)
    # alternatively
    # my_array.append(get_row(runner))
Skam
  • 7,298
  • 4
  • 22
  • 31