Learn python tuples using simple examples.

Example 1: Simple Tuple Example

This example will teach you the following:

  1. How to create a tuple
  2. How to print tuple.
  3. How to get the length or size of a tuple.
  4. How to access and print individual tuple contents.

Step 1: Create Project

Create python project or file named main.py.

Step 2: Write Code

Here is how you create a tuple:

classmates = ('Karim', 'Lucy', 'Kara')

You print or dump a whole tuple as follows:

print('classmates =', classmates)

Here is how you get and print the size or length of a tuple using the len() function:

print('len(classmates) =', len(classmates))

Here’s how you get an individual tuple element at a certain position and print it:

print('classmates[0] =', classmates[0])

Add the following code:

classmates = ('Karim', 'Lucy', 'Kara')
print('classmates =', classmates)
print('len(classmates) =', len(classmates))
print('classmates[0] =', classmates[0])
print('classmates[1] =', classmates[1])
print('classmates[2] =', classmates[2])
print('classmates[-1] =', classmates[-1])

Step 3: Run

Run the code by navigating to the project directory:

cd your_project_folder

Then execute:

python main.py

You will get the following:

classmates = ('Karim', 'Lucy', 'Kara')
len(classmates) = 3
classmates[0] = Karim
classmates[1] = Lucy
classmates[2] = Kara
classmates[-1] = Kara

Now try to modify a tupe as follows:

# cannot modify tuple:
classmates[0] = 'Adam'

An error is raised since you cannot modify a tuple:

Traceback (most recent call last):
  File "<string>", line 10, in <module>
TypeError: 'tuple' object does not support item assignment

Categorized in: