Python using enumerate inside list comprehension - Stack Overflow
Python loop through list, enumerate, and start and end at specific index, but do not modify the index - Stack Overflow
Python - index in enumerate - Stack Overflow
Python enumerate() function
Videos
Try this:
[(i, j) for i, j in enumerate(mylist)]
You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:
[pair for pair in enumerate(mylist)]
Either way, the result that gets returned is as expected:
> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Just to be really clear, this has nothing to do with enumerate and everything to do with list comprehension syntax.
This list comprehension returns a list of tuples:
[(i,j) for i in range(3) for j in 'abc']
this a list of dicts:
[{i:j} for i in range(3) for j in 'abc']
a list of lists:
[[i,j] for i in range(3) for j in 'abc']
a syntax error:
[i,j for i in range(3) for j in 'abc']
Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:
>>> {i:j for i,j in enumerate('abcdef')}
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
And a set of tuples:
>>> {(i,j) for i,j in enumerate('abcdef')}
set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])
As Óscar López stated, you can just pass the enumerate tuple directly:
>>> [t for t in enumerate('abcdef') ]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]
Don't slice, just iterate over the index like you would do in C.
saved_index=[]
for index in range(start):
for i in range(start[index], end[index]+1):
if "blah" in filelist[i]:
saved_index.append(i)
But even slices would work because you know the offset
saved_index=[]
for index in range(start):
for i,l in enumerate(filelist[start[index]:end[index]]):
if "blah" in l:
saved_index.append(start[index]+i)
Just tell enumerate to start with the start index.
saved_index=[]
for s,e in zip(start, end):
for i,l in enumerate(filelist[s:e], s):
if "blah" in l:
saved_index.append(i)
when you are using for loop with a list. It includes all the elements in the list starting from the zero'th:
if f=['x','y','z']
for i, word in enumerate(f):
print i, word
would output:
0 x
1 y
2 z
for printing every 30th line. You can use
for i in range(0,390,30):
which would output: 0, 30 ,60 90, ...
For your first question: the index starts at 0, as is generally the case in Python. (Of course, this would have been very easy to try for yourself and see).
>>> x = ['a', 'b', 'c']
>>> for i, word in enumerate(x):
print i, word
0 a
1 b
2 c
For your second question: a much better way to handle printing every 30th line is to use the mod operator %:
if i+1 % 30 == 0:
print i
# ...
This is slightly better than testing for membership in range since you don't have to worry about edge effects (i.e. since range gives a half-open interval that is open on the right end).