Dev ❤ Ops

Tuples in Python

Tuples in Python

Tuples in Python are similar to lists, but they are immutable, meaning that their values cannot be changed after they are created.

To create a tuple, you can use parentheses and separate the values with commas. For example:

my_tuple = (1, 2, 3)

You can also create a tuple using the built-in tuple() function, like so:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

You can access the elements of a tuple using indexing, just like you would with a list. For example:

print(my_tuple[0]) # Output: 1

You can also use negative indexing to access elements from the end of the tuple.

You can use the len() function to find the number of elements in a tuple, and the in keyword to check if a certain value is present in the tuple.

You can’t modify the element of tuple after its creation, if you want to change the value of tuple, you need to create a new tuple with modified values.

You can also use tuple packing and unpacking to assign multiple values to variables at once.

x, y, z = (1, 2, 3)
print(x, y, z) # Output: 1 2 3

Tuples are useful when you want to use multiple values as a single entity, such as in a function that returns multiple values. It is also useful when you want to use a collection of items that should not be changed throughout the program.

In summary, a tuple is a collection of ordered and immutable elements, which can be accessed and iterated through like a list. They are useful when you want to use multiple values as a single entity and also when you want to use a collection of items that should not be changed throughout the program.

For more information please visit python.org

This article is created based on experience but If you discover any corrections or enhancements, please write a comment in the comment section or email us at contribute@devopsforu.com. You can also reach out to us from Contact-Us Page.

Follow us on LinkedIn for updates!

Leave a comment

Your email address will not be published. Required fields are marked *