Home > Back-end >  Return slice from list comprehension
Return slice from list comprehension

Time:10-08

What's the (one-line) syntax of returning a slice from list comprehension? e.g.:

def foo(iterable):
    ls = [_ for _ in iterable]
    return ls[1:]

ANSWER: -> slice list comprehension:

[_ for _ in _][1:]

CodePudding user response:

Why can't you simply slice the list comprehension?

def foo(iterable):
    return [_ for _ in iterable][1:]

CodePudding user response:

in your case you can just:

list(iterable)[2:] 

but you also can:

[ i for i in range(10)][2:]

out[1] [2, 3, 4, 5, 6, 7, 8, 9]

just some other tips, slicing from the end:

[ i for i in range(10)][-2:]

out[2] [8, 9]

conditional list comprehension:

[ i for i in range(10) if i%2==0]
out[3] [0, 2, 4, 6, 8]
  • Related