Reputation: 23
How can I select and take elements from the third element to the last?
names = [1,2,3,45,12]
Upvotes: 1
Views: 6627
Reputation: 417
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.
Upvotes: 3
Reputation: 549
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
Upvotes: 4