Python – Create Tuple

Create Tuple in Python

In this tutorial, we will learn how to create a Tuple in Python.

You can create a Tuple in Python in many ways. Following are some of the ways we shall discuss in this tutorial with example programs.

  • Using parenthesis.
  • Using tuple() builtin function.

1. Create Tuple using parenthesis

You can initialize a variable with Tuple value using parenthesis and elements of the tuple inside parenthesis, separated by comma.

If you do not provide any items, then an empty tuple is created.

Python Program

vowels_tuple = ('a', 'e', 'i', 'o', 'u')
empty_tuple = ()

print(vowels_tuple)
print(empty_tuple)
Run Code Copy

Output

('a', 'e', 'i', 'o', 'u')
()

Create Tuple using tuple() function

tuple() builtin function accepts any iterable and creates a tuple with the elements/items provided by iterable.

1. Create Tuple from String

Let us first create a tuple from String. String is an iterable with each character as an element.

Python Program

str = 'Python'
tuple_from_string = tuple(str)
print(tuple_from_string)
Run Code Copy

Output

('P', 'y', 't', 'h', 'o', 'n')

2. Create Tuple from List

Now, we shall create a Python Tuple from List.

Python Program

my_list = ['a', 'e', 'i', 'o', 'u']
tuple_from_list = tuple(my_list)
print(tuple_from_list)
Run Code Copy

Output

('a', 'e', 'i', 'o', 'u')

3. Create Tuple from range

Create Python Tuple from range.

Python Program

my_range = range(5)
tuple_from_range = tuple(my_range)
print(tuple_from_range)
Run Code Copy

Output

(0, 1, 2, 3, 4)

4. Create Tuple from Set

You can create a tuple from Python Set by passing a set to the tuple() constructor.

Python Program

my_set = {'a', 'e', 'i', 'o', 'u'}
tuple_from_set = tuple(my_set)
print(tuple_from_set)
Run Code Copy

Output

('o', 'a', 'u', 'i', 'e')

Set is an unordered collection of items. So, when you create a tuple from set, the order in which the items are arranged in a tuple is uncertain.

Summary

In this tutorial of Python Examples, we learned how to create a tuple with some initial values or from another type like string, list, set, range, etc.

Related Tutorials

Code copied to clipboard successfully 👍