Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over only the first variable of a tuple

In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then:

for x,y,z in points:
    pass
    # do something with x y or z

What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python?

like image 355
Peter Smit Avatar asked Jun 17 '10 11:06

Peter Smit


2 Answers

Is something preventing you from not touching variables that you're not interested in? There is a conventional use of underscore in Python to indicate variable that you're not interested. E.g.:

for x, _,_ in points:
    print(x)

You need to understand that this is just a convention and has no bearing on performance.

like image 124
SilentGhost Avatar answered Oct 12 '22 20:10

SilentGhost


Yes, the underscore:

>>> a=(1,2,3,4)
>>> b,_,_,c = a
>>> b,c
(1, 4)

This is not exactly 'skipping', just a convention. Underscore variable still gets the value assigned:

>>> _
3
like image 28
unbeli Avatar answered Oct 12 '22 20:10

unbeli