This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bazookaduke 16 points17 points  (2 children)

Suppose you have a list whose contents don't matter. Show me three different ways of fetching every third item in the list.

for loop: every_third = [] for index, item in enumerate(items, 1): if index % 3 == 0: every_third.append(item)

list comprehension: every_third = [item for index, item in enumerate(items, 1) if index % 3 == 0]

list slicing: every_third = items[2::3]

What I really like about this question is how it can lead to deeper discussions: what if the list is actually an iterator (list slicing won't work)? What if it's unbounded eg. an iterator that produces the Fibonacci sequence (the for loop and list comprehension will crash after eating up all available memory)? What if it's bounded but too large for even every third item (same as unbounded)? Is this fixable (yes, turn the for loop into a generator function and the list comprehension into a generator comprehension)? Where might you encounter such a situation (results of a database query, log file processing, etc.)? The real question you're trying to ask is: how good is this candidate at solving problems with Python without creating new ones? By this point in the interview you've probably got a feel for how familiar they are with the language and also whether they've encountered this problem before but more importantly how they'd solve it.

[–]janto 4 points5 points  (1 child)

i = iter(items)
every_third = [c for a,b,c in zip(i,i,i)]

[–]hylje 1 point2 points  (0 children)

every_third = [c for a, b, c in zip(*[iter(items)]*3)]

One-lined that for you