0

How can I select and take elements from the third element to the last?

names = [1,2,3,45,12]
Zoe
  • 27,060
  • 21
  • 118
  • 148
Codeninja
  • 13
  • 2
  • @PacketLoss that's not correct – Derek Eden Apr 24 '20 at 01:41
  • 1
    check out slicing in the documentation..it's rather simple, if you have a list, you can slice a subset of itself by doing names[start:stop:step], where start=start index, stop=stop index, step=the step to take between start and stop, note python will include up to but not including the stop index..here is a good question that covers this https://stackoverflow.com/questions/509211/understanding-slice-notation – Derek Eden Apr 24 '20 at 01:46

2 Answers2

3

You can slice an array from a certain index to the end or to another position as shown below

new_names = names[2:]

The above will slice from third to the last index

Novak254
  • 439
  • 6
  • 14
3
names = [1,2,3,45,12]

You can access only certain parts of an array with slicing:

slicednames = names[2:]
[3,45,12]

This will save all elements from names to the new array, starting with the 3rd element.

If you put a second number in, you can specify the last element that is taken from the array as well:

slicednames = names[2:4]
[3,45]

This would copy only the elements 3 and 4. (The end limit is excluded, while the starting index is included.

If there is another colon followed by another number, its the size of the steps.

slicednames = names[::2]
[1,3,12]

So this would copy every second element of the array. (Starting with the first one, if not specified otherwise)

You should read about slicing, it is a basic and very useful tool to have in your belt.

Chrissu
  • 382
  • 1
  • 13