88

I'm having some trouble figuring out how to slice lists, it is illustrated as follows:

>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To my understanding, slice means lst[start:end], and including start, excluding end. So how would I go about finding the "rest" of a list starting from an element n?

7 Answers 7

138

If you're using a variable as the range endpoint, you can use None.

 start = 4
 end = None
 test[start:end]
Sign up to request clarification or add additional context in comments.

2 Comments

Oh thank you! i was looking for this, but didn't know how to search for it :). I feel the accepted answer is sort of incomplete without this, because leaving an end index is trivial and has enough documentation.
This same technique is also very useful to do the same thing with slice(4, None), where the colon approach does not work.
129

You can leave one end of the slice open by not specifying the value.

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

1 Comment

and if we want to start on the 3rd? start = ???; end = 3; my_list[start:end] what is the "empty" start value here?
21

Simply omit the end.

test[n:]

Comments

5

Leaving out the end still works when you want to skip some:

range(10)[3::2] => [3, 5, 7, 9]

Comments

3

You can also use the None keyword for the end parameter when slicing. This would also return the elements till the end of the list (or any sequence such as tuple, string, etc.)

# for list
In [20]: list_ = list(range(10))    
In [21]: list_[3:None]
Out[21]: [3, 4, 5, 6, 7, 8, 9]

# for string
In [22]: string = 'mario'
In [23]: string[2:None]
Out[23]: 'rio'

# for tuple
In [24]: tuple_ = ('Rose', 'red', 'orange', 'pink', 23, [23, 'number'], 12.0)
In [25]: tuple_[3:None]
Out[25]: ('pink', 23, [23, 'number'], 12.0)

Comments

3

Return a slice of the list after a starting value:

my_list = ['a','b','c','d']
start_from = 'b' # value you want to start with
slice = my_list[my_list.index(start_from):] # returns slice from starting value to end

1 Comment

Even though this is example code, it's best not to use list as a variable name
1

What you are looking for is to use something like:

inputs = "ababbbaAab"
for i in range(n):
    print(i, inputs[:i] + inputs[i:i+1])

The output:

0 a
1 ab
2 aba
3 abab
4 ababb
5 ababbb
6 ababbba
7 ababbbaA
8 ababbbaAa
9 ababbbaAab

See that if i == 0

then inputs[:i] == [] and inputs[i:i+1] == a

and if i == len(inputs) - 1

then inputs[:i] == [ababbbaAa] and inputs[i:i+1] == b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.