2

I know I can do this with a loop but I was wondering if there was a neater solution?

I have a list, which I want to select the first n items and place them in another list.

What I want to do is something like (pseudo code)

n = 3

x = [1,2,3,4,5,6,7,8,9,0]

y = copy n from x

print(y)

>>> [1,2,3]

Thanks

Chris Headleand
  • 6,003
  • 16
  • 51
  • 69

1 Answers1

8

You can use slicing like this

y = x[:n]
print(y)

When you say x[:n], it means that, get all the elements till index n (but not including the element at index n).

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497