For loop for second items in list of lists only. (python)

Jacxel picture Jacxel · Apr 13, 2012 · Viewed 12.6k times · Source

What I have

is something like this

def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

for _, thing, _, _ in mylist:
    print thing

# this bit is meant to be outside the for loop, 
# I mean it to represent the last value thing was in the for
if thing:
    print thing

What I want

what I want to do is avoid the dummy variables, is there a smarter way to do this than

for thing in mylist:
    print thing[1]

because then i would have to use thing[1] any other time I needed it, without assigning it to a new variable and then things are just getting messy.

newish to python so sorry if I'm missing something obvious

Answer

Kien Truong picture Kien Truong · Apr 13, 2012

You could hack a generator expression

def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

for thing in (i[1] for i in mylist):
    print thing

# this bit is meant to be outside the for loop, 
# I mean it to represent the last value thing was in the for
if thing:
    print thing