Tuples

A tuple is a collection that cannot be modified.

Variables can be of the datatype tuple. A tuple is defined using parenthesis.
If you want to change the data during program execution, use a list instead of a tuple.

Related Courses

Example

A tuple with one item ( a comma is needed in the end ):

A tuple with multiple items:

Note: Even with one element, the comma is needed.

 

Accessing tuples

To access individual elements, we use square brackets. To print the first element (Python starts counting from zero):

To print the second element:

To print the last element, you can count from the back using the minus sign.

 

Previous Post
Next Post

4 Comments

  • Janis McSweeney says:

    Hi,
    I don’t understand why the last numeric character in the multiple tuple does not have a comma after it?
    If it is a stand alone single character, it has a comma; and yet if it is the last numeric character in a string of numerics, then each numeric has a comma after it – with the exception of the last numeric, why?

    • ninja says:

      A comma on the end is required with a single element, but not if you have multiple elements. A tuple is defined as: values separated by commas.

      Why a comma for one element? Python has otherwise no way of knowing its a tuple, consider:

      Python wouldn’t know if it’s a tuple, in this case it’s just a number. That’s why a tuple always needs at least one comma. If we have more than one number, it already has commas.

  • kevin says:

    what‘s the difference between Lists and tuples? Is the tuples similar with enumeration of C language?

Leave a Reply