Python Tuples

Tuples are ordered, immutable collections of items. Once a tuple is created, its elements cannot be changed. Tuples are often used to store related pieces of information and can contain items of different data types.

Creating Tuples

You can create a tuple by placing comma-separated values inside parentheses.

Tuples can store multiple items in a single variable. They can include different data types such as strings, integers, floats, and even other tuples.

Tutorials dojo strip
Python

Accessing Tuple Items

You can access individual items in a tuple using indexing. Python uses zero-based indexing.

The index 0 accesses the first item in the tuple, while the index -1 accesses the last item.

Python

Immutable Nature of Tuples

Tuples are immutable, meaning you cannot change their items after creation.

Attempting to change an item in a tuple will result in an error.

Python

Tuple Methods

Tuples have built-in methods like count() and index().

  • count(): Returns the number of times a specified value appears in the tuple.
  • index(): Returns the index of the first occurrence of a specified value.
Python

Using Tuples for Multiple Assignments

Tuples are commonly used to assign multiple variables at once.

You can unpack a tuple into multiple variables.

Python

Python Tuples Example Code

This program creates a tuple of fruits and demonstrates accessing items, using tuple methods, and multiple assignments.

Python




Python Labs

Tutorials dojo strip