Skip to content Skip to sidebar Skip to footer

Best Style For Iterating Over A Small Number Of Items In Python?

I was just reading a presentation on python and I noted that the author had missed out the round brackets of the tuple for the items to iterate over, and it struck me that I might

Solution 1:

I make a point to do neither. I've found that code readability improves if you assign the tuple to a descriptive variable.

For instance:

for name in relative_names:
    print name

vs

for name in"Tyler", "Robert", "Marla", "Chloe", "Lou":
    print name

Solution 2:

I would always prefer:

>>># Some setup...some_values = 1, 'Hi', True,>>>>>># Style 3: named tuple...for value in some_values:...print(value)... 
1
Hi
True

Solution 3:

I'd go with Style 2, as you can actually understand what you are iterating over:

>>># Style 2: Explicit tuple>>>for i in (x, y, z):
        print(i)

Style 1 seems a bit confusing to me for some reason.

Solution 4:

In this case explicit is better than implicit, the tuple should be obvious.

I think there are bigger fish to fry though :) Anybody will know what you are up to in either case, and it's a tiny change.

Post a Comment for "Best Style For Iterating Over A Small Number Of Items In Python?"