Top Python Interview Questions

Chris Angelico rosuav at gmail.com
Sat May 27 00:15:07 EDT 2017


On Sat, May 27, 2017 at 12:19 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Sat, 27 May 2017 09:37 am, Chris Angelico wrote:
>
>> On Sat, May 27, 2017 at 8:56 AM, Larry Martell <larry.martell at gmail.com>
>> wrote:
>>> If they write a loop with range(1,10) they are going in the 'no' pile.
>>> If they write a loop with range(1,11) they go in the maybe pile
>>> If the write sum([i*i for i in range(1,11)]) and sqrt(sum([i for i in
>>> range(1,11)])) they are going in the yes pile.
>>
>> And if they leave off the square brackets, even better. :)
>
> If they leave out the square brackets, the code might be slower.
>
> I know that ''.join() is about 30% faster with a list comprehension than a
> generator expression, but I'm not sure about sum().

That's probably because "".join() can do two passes over a list, one
to sum the lengths and one to actually copy data. But summing integers
can be done without. That said, though, empirical testing seems to
show that the comprehension is a bit faster. My guess is that that
would change on larger data sets though.

ChrisA



More information about the Python-list mailing list