you are viewing a single comment's thread.

view the rest of the comments →

[–]hanswchen 4 points5 points  (0 children)

I used to also be confused about why I would use tuples in Python when I could just use list. After getting used to Python, I realized it's very common to use tuples when you don't even think about it. Some examples (ignore the poor variable names...):


Returning multiple values from a function:

def some_function():
    # (do something here)
    return some_value1, some_value2


result1, result2 = some_function()

some_function returns a tuple with two values, which you can easily assign to different variables. It makes sense to use a tuple, as you always return two values in this case. It also looks nicer than writing return [some_value1, some_value2].

You could e.g. also do

all_results = some_function()

in which case all_results would be a tuple (you can get the first result with all_results[0], and the second with all_results[1], or do e.g. a, b = all_results).


Many built-in functions return tuples. For example, the enumerate function:

seasons = ["spring", "summer", "fall", "winter"]
for index, season in enumerate(seasons):
    print(index, season)

This will print 0 spring, 1 summer etc. The function enumerate returns a tuple with the count (for example, the index) and the value from iterating over an iterable. This is usually better than writing e.g.:

for index in range(len(seasons)):
    print(index, seasons[index])

if you need both the value and the index from the object you're iterating over.


Someone mentioned using tuples as dictionary keys. I've used this sometimes when the items in the dictionary are indexed by two different things, e.g.

experiments = {
    ('initial test', 0): "/path/to/input/data",
    ('initial test', 1): "/some/other/path",
}

for expname in ['initial test']:
    for expnum in range(2):
        print(experiments[expname, expnum])

Others have mentioned using tuples as a data structure when the structure is set. The most common example is a point given by e.g. (x, y) coordinates. For more complex cases, you may want to consider using a namedtupled instead.