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.

Tutorials dojo strip

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




Accessing Tuple Items

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

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




Immutable Nature of Tuples

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

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




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.




Using Tuples for Multiple Assignments

Tuples are commonly used to assign multiple variables at once.

Explanation: You can unpack a tuple into multiple variables.




Python Tuples Example Code

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




Python Labs

Tutorials dojo strip