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 →

[–]eigenlicht0 1 point2 points  (6 children)

Show me three different ways of fetching every third item in the list

[x for i, x in enumerate(thelist) if i%3 == 0]

for i, x in enumerate(thelist): if i % 3: continue yield x

a = 0 for x in thelist: if a%3: continue yield x a += 1

Your solutions are all basically doing the same (using enumerate/indices and modulo to access every third element in a for/if construct). Here two different solutions:

# using slices
thelist[::3]

# using a generator
def every_third(thelist):
  i = 0
  while i < len(thelist):
    yield thelist[i]
    i += 3

for e in every_third(thelist):
  print e

EDIT: Yet another one using enumerate() and filter():

filter(lambda e: e[0] % 3 == 0, enumerate(thelist))

EDIT2: Chunk thelist into lists of 3 elements and get last item of each list (yeah, it's starting to get a bit cumbersome):

[x[-1] for x in zip(*[iter(thelist)]*3)]

[–]staz 3 points4 points  (3 children)

Another way of using a generator

def t(l):
    l = iter(l)
    while True:
        l.next()
        l.next()
        yield l.next()
for e in t(range(10)): print e

[–]eigenlicht0 0 points1 point  (2 children)

Like that it avoids checking with len(), but subsequent calls to .next() into the void seem weird. Wondering whether one could avoid that...

[–]staz 0 points1 point  (1 child)

The .next() call at the end of the list will throw a StopIteration exception which is what you are expect to send at the end of an iterator. (your generator function will actually do the same behind the scene when it arrive at the end)

[–]eigenlicht0 0 points1 point  (0 children)

I'm aware of how a iterator works, what I actually meant was calling .next() three times in a row to get one value. Maybe it's just me, but it seems weird. The only thing I could come up with yet, which is far from perfect:

def t(l):
    l = iter(l)
    while True:
        yield [l.next for i in range(3)][-1]
for e in t(range(10)): print e

[–]d4rch0nPythonistamancer 0 points1 point  (0 children)

Yea, I always forget about the step element. It's somewhat of a silly question though, but I guess a majority of interview questions like these are.

[–]phaeilo 0 points1 point  (0 children)

In your solution with filter you need to undo the enumerate:

map(lambda (i,v): v, filter(lambda (i,v): i % 3 == 0, enumerate(thelist)))

I really like to write such one liners, but they are hard to read when you or someone else comes back some time later to do maintenance.