Monday, 29 January 2024

Convert a list to tuple in Python

Tuples in Python are similar to lists in that they are ordered collections of items, but they differ in being immutable, meaning once created, their contents cannot be changed.

Following are the various approaches to convert a list to a tuple.

 

Approach 1: Using tuple() function.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = tuple(primes_list)

In the above Python snippet, a list of prime numbers is first created and then converted into a tuple. Initially, primes_list is defined as a list containing the first five prime numbers: 2, 3, 5, 7, and 11. Lists in Python are mutable, ordered collections of items, which in this case are integer values representing prime numbers. Following this, primes_tuple is created by converting primes_list into a tuple using the tuple() function.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = tuple(primes_list)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 2: Using unpacking (*) operator.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = (*primes_list,)

In the above Python code, a list of prime numbers is initially defined, and then this list is converted into a tuple using the unpacking operator *.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = (*primes_list,)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 3: Using for loop.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = ()

for item in primes_list:
   primes_tuple += (item,)

Above snippet demonstrates a process for converting a list of prime numbers into a tuple through iteration. The code begins by defining primes_list, a list containing the first five prime numbers: 2, 3, 5, 7, and 11. The conversion from the list to the tuple is achieved using a for loop. The loop iterates over each item in primes_list. Within the loop, the current item is added to primes_tuple using the += operator, which in the context of a tuple, creates a new tuple by concatenating the existing primes_tuple with a new tuple containing the current item, (item,).

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = ()
>>> 
>>> for item in primes_list:
...    primes_tuple += (item,)
... 
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment