Home > OS >  What's Wrong In This Python Program [closed]
What's Wrong In This Python Program [closed]

Time:10-01

num1=int(input("Enter Number of Elements For first list :"))
list1=[]
for i in range(num1):
    ele=[input("Enter element of list 1 :")]
    list1.append(ele)


new_list = [(i,pow(i,2)) for i in list1]

print(list1)

print(new_list)

Traceback (most recent call last):
  File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <module>
    new_list = [(i,pow(i,2)) for i in list1]
  File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <listcomp>
    new_list = [(i,pow(i,2)) for i in list1]
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

CodePudding user response:

Problem:

  • You cannot use pow() on list, pow is always called on numbers

Solution:

  • Instead of appending a list to list1, just convert the input to int and append the number ele.

This code should work fine

num1 = int(input("Enter Number of Elements For first list :"))
list1 = []
for i in range(num1):
    ele = int(input("Enter element of list 1 :"))
    list1.append(ele)

new_list = [(i, pow(i, 2)) for i in list1]

print(list1)
print(new_list)

Output:

Enter Number of Elements For first list :2
Enter element of list 1 :10
Enter element of list 1 :20
[10, 20]
[(10, 100), (20, 400)]
  • Related