What is a tuple?

I get asked this from time to time, so for the fun of it, I’ll post this:

Tuples are immutable lists in python (and other languages).  Very lightweight, unchangable arrays.  They are used for storing multiple values in one variable (usually a fixed number of values).

x = (1, 2, 3, 'abc')
x[0]
-> 1
x[1] 
-> 2
x[2] 
-> 3

x[3] 
-> abc
x["bob"]
-> TypeError: tuple indices must be integers, not str

Tuples are immutable lists in python (and other languages).  Very lightweight, unchangable arrays.
x = (1,2,3)
x[0] == 1
x[1] == 2
x[2] == 3
x[“bob”] == “tuple indices must be integers”

A common example is storing x,y coordinances.  You could use a tuple for that:

point = (12,38)

Python can unpack tuples also.

x,y = (12,38)
x
-> 12
y
-> 38

Enjoy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s