Site icon Care All Solutions

Tuples

Tuples in Python

Tuples are immutable sequences of Python objects. They are similar to lists but cannot be changed once created.

Creating Tuples

Tuples are created by enclosing a comma-separated sequence of values within parentheses.

Python

# Empty tuple
empty_tuple = ()

# Tuple with elements
numbers = (1, 2, 3, 4, 5)
mixed_tuple = (10, "hello", True, 3.14)

Accessing Tuple Elements

Tuples can be accessed using indexing, similar to lists.

Python

numbers = (1, 2, 3, 4, 5)
first_number = numbers[0]  # Output: 1
last_number = numbers[-1]  # Output: 5

Tuple Operations

While tuples are immutable, they support some operations:

Python

tuple1 = (1, 2, 3)
tuple2 = (4, 5)
combined_tuple = tuple1 + tuple2  # Output: (1, 2, 3, 4, 5)

Key Points

How do I create a tuple?

Enclose elements within parentheses, separated by commas.

Can I access elements in a tuple using indexing?

Yes, you can use indexing to access elements.

Can I modify elements in a tuple?

No, tuples are immutable.

What is the difference between a tuple and a list?

Tuples are immutable while lists are mutable.

When should I use a tuple instead of a list?

Use tuples when the data is fixed and doesn’t need to be modified.

Can a tuple contain another tuple?

Yes, tuples can be nested.

Can I use tuples as dictionary keys?

Yes, tuples can be used as dictionary keys if all elements in the tuple are hashable.

Read More..

Exit mobile version