Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: slices of enumerate

Tags:

python

list

slice

I want to iterate within a slice of a list. Also, I want to know the indexes of the element under my iteration.

I want to make something like

for i, elm in enumerate(test_list)[7:40]:
    print i, elm
    #i must start with 7

Alas, it says, that 'enumerate' object has no attribute '__getitem__'

How can I get it in most pythonic way?

like image 500
Felix Avatar asked Apr 18 '14 17:04

Felix


People also ask

What are slices in Python?

Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. Slices can also be applied on third-party objects like NumPy arrays, as well as Pandas series and data frames.

What does enumerate () do in Python?

Python enumerate() Function The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object. The enumerate() function adds a counter as the key of the enumerate object.


2 Answers

You can use islice:

from itertools import islice

for i,elm in islice(enumerate(some_list),7,40):
    print i,elm
like image 69
roippi Avatar answered Sep 24 '22 10:09

roippi


enumerate returns an iterator, which does not support index-based access. You can however slice the original list first, and just start at a different index with enumerate:

for i, elm in enumerate(test_list[7:40], 7):
    print i, elm
like image 40
poke Avatar answered Sep 23 '22 10:09

poke