Q:

Python program to create a list of tuples from given list having number and its cube in each tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Creating a list of tuples from given list having number and its cube in each tuple

We have a list of elements and we need to create another list of elements such that each element of the new list is a tuple. And each of the tuples consists of two values one the element from the list and the second will be the cube of the value.

Example:

Input: 
list = [4, 1, 6, 2]

Output: 
[(4, 64), (1, 1), (6, 216), (2, 8)]

We simply need to iterate over all the elements of the list and then for each element create a tuple consisting of the element and its cube and then append it to a list.

This can be done by simply loop and also to shorten the code we can use comprehension techniques. Here is a code depicting both the methods.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# Creating a list
myList = [6, 2, 5 ,1, 4]

# Creating list of tuples 
tupleList = [] 
for val in myList:
    myTuple = (val, (val*val*val))
    tupleList.append(myTuple)

# print the result
print("The list of Tuples is " , str(tupleList))

Output:

The list of Tuples is  [(6, 216), (2, 8), (5, 125), (1, 1), (4, 64)]

Using comprehension

# Creating a list
myList = [6, 2, 5 ,1, 4]

# Creating list of tuples 
tupleList = [(val, (val*val*val)) for val in myList]

# print the result
print("The list of Tuples is " , str(tupleList))

Output:

The list of Tuples is  [(6, 216), (2, 8), (5, 125), (1, 1), (4, 64)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to remove all tuples of length K... >>
<< Python program to find the maximum and minimum K e...