0

Other than using a loop, is there a method to take a segment from a list.

For example, if I had the list:

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

and I wanted to take a segment from the 3rd item to the 5th I would end up with...

segment = [4,5,6]

I know this can be done with a loop but I was wondering if there was a more "pythonic" aproach?

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

1 Answers1

4

l[3:6] is what you are looking for.

This uses list slicing. 3 is the start index. 6 is the end index. We mention 6 as the end index (even though index of 6 is 5) because the slice notation requires the index of the element after the last element we need to be part of the segment.

Demo:

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

This answer explains how slicing on Python lists work - Explain Python's slice notation

Community
  • 1
  • 1
shaktimaan
  • 11,962
  • 2
  • 29
  • 33