Q:

Numbering elements in a list

I have a list that goes:
[1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1]
I'd like to print all the elements of the list with a value of greater than 2 but also print the position in the list, I can print the elements by themselves with:
for bonds in number_of_bonds:       
    if bonds >= 2:
         print bonds

But if I use enumerate it will instead print all the items in the list with their position like this:
(0, 1)
(1, 1)
(2, 3)

etc
So what is the correct way to do this?

A:

for your problem you can do 
[(i, j) for i,j in enumerate(l) if j > 2]

output:
[(2, 3),
 (3, 3),
 (4, 3),
 (5, 3),
 (6, 3),
 (7, 3),
 (8, 3),
 (9, 3),
 (10, 3),
 (11, 3),
 (12, 3),
 (13, 3),
 (14, 3),
 (15, 3)]

A:

lst = [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1]
print [(i, e) for (i, e) in enumerate(lst) if e > 2]

[(2, 3),
 (3, 3),
 (4, 3),
 (5, 3),
 (6, 3),
 (7, 3),
 (8, 3),
 (9, 3),
 (10, 3),
 (11, 3),
 (12, 3),
 (13, 3),
 (14, 3),
 (15, 3)]

If your list is huge, a better way would be to use a generator via () to generate each element on the fly instead of all at once in memory:
result = ((i, e) for (i, e) in enumerate(lst) if e > 2)

for i in result:
    print i

then the output will be:
(2, 3)
(3, 3)
(4, 3)
(5, 3)
(6, 3)
(7, 3)
(8, 3)
(9, 3)
(10, 3)
(11, 3)
(12, 3)
(13, 3)
(14, 3)
(15, 3)

Note that a generator can only be read once, meaning if you loop over result again nothing will get printed.

