Questions tagged [tuples]

In programming, tuples are simple *product types*, representing ordered collections of types.

A tuple, like a struct in some languages, is a collection of items of any type delimited with parentheses. Unlike structs, however, tuples are immutable. Many programming languages have "taken" tuples from functional programming languages like F#, where they are used very often.

In Python, for example, tuples are used to encapsulate the actual parameters of functions and methods. Tuples are related to currying of functions, which is a transformation that turns a function taking a tuple with n fields, into a n functions each taking one argument.

Creating a tuple

>>> l = [1, 'a', [28, 3.5]] #square brackets
>>> t = (1, 'a', [28, 3.5]) #round parentheses 
>>> type(t), type(l)
(<class 'tuple'>, <class 'list'>)
>>> t
(1, 'a', [6, 3.5])
>>> tuple(l)
(1, 'a', [6, 3.5])
>>> t == tuple(l)
True
>>> t == l
False

Also the statement

t = 12345, 54321, 'hello!'
 

is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible, e.g.:

>>> brian, x_ray, lemba = t

This is called, appropriately enough, tuple unpacking. Tuple unpacking requires that there be the same number of variables as items in tuple. Note that multiple assignment is really just a combination of tuple packing and tuple unpacking!

A one item tuple is created by an item in parens followed by a comma: e.g

>>> t = ('A single item tuple',)
>>> t
('A single item tuple',)

Also, tuples will be created from items separated by commas, like so:

>>> t = 'A', 'tuple', 'needs', 'no', 'parens'
>>> t
('A', 'tuple', 'needs', 'no', 'parens')

References

11941 questions
313
votes
9 answers

Are tuples more efficient than lists in Python?

Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
readonly
  • 343,444
  • 107
  • 203
  • 205
297
votes
2 answers

How to unzip a list of tuples into individual lists?

I have a list of tuples l = [(1,2), (3,4), (8,9)]. How can I, succinctly and Pythonically, unzip this list into two independent lists, to get [ [1, 3, 8], [2, 4, 9] ]? In other words, how do I get the inverse of what zip does?
VaidAbhishek
  • 5,895
  • 7
  • 43
  • 59
287
votes
11 answers

Convert tuple to list and back

I'm currently working on a map editor for a game in pygame, using tile maps. The level is built up out of blocks in the following structure (though much larger): level1 = ( (1,1,1,1,1,1) (1,0,0,0,0,1) (1,0,0,0,0,1) …
user2133308
  • 2,871
  • 2
  • 13
  • 4
269
votes
2 answers

Unpacking a list / tuple of pairs into two lists / tuples

I have a list that looks like this: my_list = [('1','a'),('2','b'),('3','c'),('4','d')] I want to separate the list in 2 lists. list1 = ['1','2','3','4'] list2 = ['a','b','c','d'] I can do it for example with: list1 = [] list2 = [] for i in list: …
Breixo
  • 2,860
  • 2
  • 15
  • 9
256
votes
7 answers

How to convert comma-delimited string to list in Python?

Given a string that is a sequence of several values separated by a commma: mStr = 'A,B,C,D,E' How do I convert the string to a list? mList = ['A', 'B', 'C', 'D', 'E']
O.rka
  • 29,847
  • 68
  • 194
  • 309
240
votes
4 answers

How does tuple comparison work in Python?

I have been reading the Core Python programming book, and the author shows an example like: (4, 5) < (3, 5) # Equals false So, I'm wondering, how/why does it equal false? How does python compare these two tuples? Btw, it's not explained in the…
Paulo
  • 6,982
  • 7
  • 42
  • 56
236
votes
10 answers

Python add item to the tuple

I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',) but when I try to add new one using mytuple = mytuple + new.id got error can only concatenate tuple (not "unicode")…
Goran
  • 6,644
  • 11
  • 34
  • 54
235
votes
1 answer

What is the inverse function of zip in python?

I've used the zip function from the Numpy library to sort tuples and now I have a list containing all the tuples. I had since modified that list and now I would like to restore the tuples so I can use my data. How can I do this?
user17151
  • 2,607
  • 3
  • 18
  • 13
232
votes
6 answers

How to form tuple column from two columns in Pandas

I've got a Pandas DataFrame and I want to combine the 'lat' and 'long' columns to form a tuple. Int64Index: 205482 entries, 0 to 209018 Data columns: Month 205482 non-null values Reported by …
elksie5000
  • 7,084
  • 12
  • 57
  • 87
228
votes
6 answers

Convert a namedtuple into a dictionary

I have a named tuple class in python class Town(collections.namedtuple('Town', [ 'name', 'population', 'coordinates', 'population', 'capital', 'state_bird'])): # ... I'd like to convert Town instances into…
Without Me It Just Aweso
  • 4,593
  • 10
  • 35
  • 53
212
votes
7 answers

What's the difference between lists enclosed by square brackets and parentheses in Python?

>>> x=[1,2] >>> x[1] 2 >>> x=(1,2) >>> x[1] 2 Are they both valid? Is one preferred for some reason?
qazwsx
  • 25,536
  • 30
  • 72
  • 106
208
votes
8 answers

Why can tuples contain mutable items?

If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
qazwsx
  • 25,536
  • 30
  • 72
  • 106
203
votes
3 answers

Getting one value from a tuple

Is there a way to get one value from a tuple in Python using expressions? def tup(): return (3, "hello") i = 5 + tup() # I want to add just the three I know I can do this: (j, _) = tup() i = 5 + j But that would add a few dozen lines to my…
BCS
  • 75,627
  • 68
  • 187
  • 294
196
votes
7 answers

python tuple to dict

For the tuple, t = ((1, 'a'),(2, 'b')) dict(t) returns {1: 'a', 2: 'b'} Is there a good way to get {'a': 1, 'b': 2} (keys and vals swapped)? Ultimately, I want to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the…
Jake
  • 12,713
  • 18
  • 66
  • 96
190
votes
2 answers

How does std::tie work?

I've used std::tie without giving much thought into it. It works so I've just accepted that: auto test() { int a, b; std::tie(a, b) = std::make_tuple(2, 3); // a is now 2, b is now 3 return a + b; // 5 } But how does this black magic…
bolov
  • 72,283
  • 15
  • 145
  • 224