Juan1403
Juan1403

Reputation: 5

How to divide or multiply between elements of a tuple in python?

I have the next tuple as result of a sql query:

tuple1 = [(245, 57)]
tuple2 = [(11249, 5728)]
tuple3 = [(435, 99)]

and I need to divide the 57 between 245 and the same with the rest.

I can access individual elements with:

[x[0] for x in rows]

but when I do:

a = [x[1] for x in rows] / [x[0] for x in rows]

I get TypeError: unsupported operand type(s) for /: 'list' and 'list'

Upvotes: 0

Views: 420

Answers (3)

user57284
user57284

Reputation: 62

Another option would be

list(map(lambda x: x[1]/x[0] if x[0] else 0,rows))

Upvotes: 0

user2390182
user2390182

Reputation: 73470

Using multiple names can increase readability:

a = [y / x for x, y in rows]

Upvotes: 0

Danny Varod
Danny Varod

Reputation: 18098

a = [x[1] for x in rows] / [x[0] for x in rows]

will attempt to divide a list by a list.

What you meant to do is:

a = [x[1] / x[0] for x in rows]

which is divide elements per item in list.

Upvotes: 1

Related Questions