jamesB
jamesB

Reputation: 528

Return slice from list comprehension

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:]

Upvotes: 0

Views: 289

Answers (2)

Guinther Kovalski
Guinther Kovalski

Reputation: 1919

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]

Upvotes: 1

Alex
Alex

Reputation: 516

Why can't you simply slice the list comprehension?

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

Upvotes: 2

Related Questions