I want to write a program in python for Square and take the csv input file

When I tried to run this code, I got this error

Traceback (most recent call last): File "txt_square.py", line 7, in <module>`enter code here` sqr = [elem **2 for elem in sqr_lst] TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int' import csv import math with open('/home/amankumar/test.csv', 'rb') as fl: reader = csv.reader(fl) sqr_lst = list(reader) sqr = [elem **2 for elem in sqr_lst] print sqr 
+5
source share
2 answers

Actually what is happening here

if you iterate over the reader (in your code), this will return you a list of str list like this: -

[[5], [6], [7], [8], [9], [1], [2]], ['4']]

so you can just use this code set [int(i[0])**2 for i in reader]

or you can apply any checks that are required in the list comprehension.

+5
source

The csv reader object contains strings that are a list of elements, and as the error indicates, you cannot use operand ** for the list and integer. If you want to perform this operation between elements that you need to iterate over the lines.

You can familiarize yourself with the list:

 sqrs = [[i **2 for for i in elem] for elem in sqr_lst ] 

Then the result will be a nested sqr list of all elements (each nested list is a string)

+3
source

All Articles