Python Tuples

Tuples are another type of data structure in Python that are similar to lists but with one key difference: tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are often used to store related pieces of information together. In this lesson, we will cover the basics of tuples and how to work with them.

Creating Tuples

You can create a tuple in Python by enclosing items in parentheses () and separating them with commas. For example:

person = ('John', 30, 'Male')
coordinates = (3, 4)

Accessing Elements

You can access elements in a tuple using indexing, just like with lists. Indexing starts at 0 for the first element. For example:

print(person[0])  # Output: 'John'
print(coordinates[1])  # Output: 4

Immutable Nature

As mentioned earlier, tuples are immutable, so you cannot change the value of an element once it has been assigned. Attempting to do so will result in an error. For example:

coordinates[0] = 5  # This will raise an error

Use Cases

Tuples are often used when you want to store a collection of items that should not be changed, such as coordinates, dates, or configuration settings.

Conclusion

Tuples are a useful data structure in Python for storing immutable collections of data. By understanding how to create and work with tuples, you can write more robust and efficient Python code.



[ Footer Placeholder]