DEV Community

Max
Max

Posted on • Updated on

Python tuple tutorial

Python tuple is a collection of ordered, immutable elements. Python Tuples are similar to lists, but they cannot be modified once created. Tuples are defined using parentheses instead of square brackets used for lists.

Example 1 - Creating a tuple with multiple values:

fruits = ("apple", "banana", "cherry", "orange")
Enter fullscreen mode Exit fullscreen mode

Example 2 - Creating a tuple with single value:

single_value_tuple = ("apple",)
Enter fullscreen mode Exit fullscreen mode

Note: A tuple with a single value must have a comma at the end.

Example 3 - Accessing tuple elements:

fruits = ("apple", "banana", "cherry", "orange")
print(fruits[1]) # Output: banana
Enter fullscreen mode Exit fullscreen mode

In the above example, we defined a tuple called "fruits" that contains four elements. We then accessed the second element of the tuple using the indexing operator and printed it.
The output is "banana".

How to print a Python tuple using a loop

Example 4:

# Define a tuple
my_tuple = ('apple', 'banana', 'cherry', 'orange')

# Print the elements of the tuple using a loop
for item in my_tuple:
    print(item)
Enter fullscreen mode Exit fullscreen mode

This code will print each element of the tuple my_tuple on a separate line:

apple
banana
cherry
orange
Enter fullscreen mode Exit fullscreen mode

You can replace my_tuple with any other tuple that you want to print using a loop.

Explore Other Related Articles

Python Lists tutorial
Python dictionaries comprehension tutorial
Python comparison between normal for loop and enumerate
Python if-else Statements Tutorial
Python set tutorial

Top comments (0)