0
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]

I need to obtain a specific length of elements form a list starting at a specific index in Python. For instance I would like to get the three next elements from the [2] element above. Is there anyway to get the three elements from the specific index? I wont always know the next amount of elements I want to get, sometimes I may want to get two elements, sometimes eight elements, so x elements.

I know I can do my_list[2:] to get all of the elements from the third element to the end of the list. What I want to do is specify how many elements to read after the third element. Conceptually in my mind the example above would look like my_list[2:+3] however I know this wont work.

How can I achieve this or is it better to define my own function to give me this functionality?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
WizardsSleeve
  • 185
  • 2
  • 4
  • 11

3 Answers3

3

You are actually very close:

>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> x = 3
>>> my_list[2:2+x]
[3, 4, 5]
>>>

As you can see, the answer to your question is to slice the list.

The syntax for slicing is list[start:stop:step]. start is where to begin, stop is where to end, and step is what to count by (I didn't use step in my answer).

  • ty - @iCodez for the link on your profile to "Laws of Software Development" - I realize this has nothing to do with your answer :) – beginAgain May 13 '19 at 16:52
1
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
n = 3
print my_list[2:2+n]

Nothing smart here. But, you can pull n out and tweak it the way you want.

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
0

you should simply use

my_list[2:2+3]

and in general

list[ STARTING_INDEX : END_INDEX ]

which is equivalent to

list[ STARTING_INDEX : STARTING_INDEX + LENGTH ]




>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> my_list[2:3]
[3]
>>> my_list[2:2+3]
[3, 4, 5]
lejlot
  • 64,777
  • 8
  • 131
  • 164
  • 1
    In general `[START_INDEX : END_INDEX : STEP]`. And all of them can also be negative or can be omitted. – Bakuriu Aug 10 '13 at 17:39