How to Create a Tuple in Python



Python


In this article, we show how to create a tuple in Python.

A tuple is data type in Python which is similar to a list but for which the data is immutable, meaning unchangeable.

Most people are familiar with lists. A list can be a series of numbers, strings, etc.

For example a list in Python can be ['Earl', 'Jack', 'Tom'] or [0,1,2,3,4,5,6]

In the first example, above, it is a list of strings. In the second example , it is a list of numbers.

If we want in Python, we can change elements of the list above.

This is shown below.



You see how we were able to change an element of the list above. Lists contain elements which are mutable, or changeable.

Tuples, on the other hand, cannot be changed.

In order to create a tuple, parentheses are used instead of brackets, which are used to create lists.

Below is how we create a tuple in Python.



So, above, we've now created a tuple.

If you used the Python type() function, you would see that the students variable above is of the class Tuple.

Now let's see what happens if we try to change an element within a tuple, shown in the code below.



So you can see that tuples, unlike lists are immutable. You cannot change elements in a tuple. If you want to be able to change elements, then you need to convert the tuple to a list, which allows elements to be changed. This can be done by doing a type conversion with the Python list() function.

How to Convert a List to a Tuple

So the next thing we show is how to convert a list to a tuple.

Let's say we have a list and we want to convert this list to a tuple.

We can convert a list to a tuple using the Python tuple () function.

This is shown in the code below.



So you can see above that we started out with a list and then we converted this list to a tuple using the tuple() function.

So this is how we can create a tuple and convert a data type to a tuple in Python.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...