ADVERTISEMENT
ADVERTISEMENT

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

Here, we have a list of values and we need to create another list that has each element as a tuple which contains the number and its cube.
Submitted by Shivang Yadav, on June 07, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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.

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)]

Python Tuple Programs »



ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.