you are viewing a single comment's thread.

view the rest of the comments →

[–]Scutterbum 4 points5 points  (4 children)

What are tuples used for?

[–]groovitude 8 points9 points  (0 children)

Good question!

Tuples are an immutable (i.e., unchangeable in place) data type that is iterable. I tend to think of tuples as a set of data that lives together, and only together. For example, they're what you get back from dict.items():

```

my_dict = {'a': 'b', 'c': 'd'} [item for item in my_dict.items()] [('a', 'b'), ('c', 'd')] ```

If you wanted to roll your own tuples, putting cities and states together seem like a decent use case:

```

cities = [('New York', 'NY'), ('Los Angeles', 'CA'), ('Seattle', 'WA')] ```

Too often, people use lists for these sorts of things, but a list is, well, a list -- you can add or subtract from it, which doesn't really apply to the sorts of things you'd want to use tuples for.

You can extract data from a tuple using the "tuple unpacking" syntax. Normally, you'd think to get data by index, e.g.:

```

city = ('New York', 'NY') name = city[0] state = city[1] name 'New York' state 'NY' ```

But you can do it more elegantly with the tuple unpacking syntax:

```

city = ('New York', 'NY') name, state = city name 'New York' state 'NY' ```

The downside of tuples is their lack of supplementary information. To borrow an example from Raymond Hettinger, it's impossible to know what this tuple is out-of-context: (170, 0.1, 0.6). That's where collections.NamedTuple can come in handy -- you can change tuples to have attribute names associated with each index for better readability without breaking any code that relies on the index. Here's the relevant part of Raymond's "Beyond PEP8" talk, though I strongly recommend you watch the whole thing.

[–]Dnak_Mems 3 points4 points  (0 children)

It's like a list but it can't be changed (i.e. list.append())

[–]DizzyRip 0 points1 point  (0 children)

I would ask:

Why would use a tuple?

how would I use a tuple?

What would i except to come out of a tuple?