0

Say I have a list arr and an index i within [0:len(arr)], how do I get all the elements starting from arr[i] up to arr[-1] in a Pythonic way? For example:

arr = 'abcdef' 
i = 3

I basically want to get b = 'def' I tried

b = a[i:-1]

but obviously that'll leave out the last element. Also, my list sometimes has only 1 element, so i = 0. How do I safely treat that edge case? Thank you!

Huy D
  • 554
  • 4
  • 7
  • 1
    See https://stackoverflow.com/a/509295/1965736 - what you are looking for is called slicing – philngo Mar 11 '18 at 02:33
  • 2
    You are looking for slicing, existing questions cover the topic. Try this one: [understading python list slicing](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – Lost Mar 11 '18 at 02:33

1 Answers1

3

You could use python list slicing like this:

b = arr[i:]    # This prints 'def' when arr = 'abcdef' and i = 3

This will print everything from the ith position to the end. And if i is greater than the string length, it'll print an empty string.

pgngp
  • 1,552
  • 5
  • 16
  • 26