LAS
LAS

Reputation: 179

How to add tuple value

Am trying to add the values in my tuple to get the total figure with the below code

Black = (("Hans","100"),("Frank","20.5"))

for v in Black:
    print(v[1])
    print (v[1]+v[1])

But when i do it this way it concatenate the values like 100100 and not total figure of the values

Upvotes: 0

Views: 42

Answers (2)

dfundako
dfundako

Reputation: 8324

You have two options:

1) Take the quotes off the values in the tuple:

Black = (("Hans",100),("Frank",20.5))
for v in Black:
       print(v[1])
       print (v[1]+v[1])

2) Convert the strings to float during the loop:

Black = (("Hans","100"),("Frank","20.5"))
for v in Black:
       print(v[1])
       print (float(v[1])+float(v[1]))

3) If your goal is the sum all the [1] index values in your list of lists:

Black = (("Hans",100),("Frank",20.5))
sum([x[1] for x in Black])

Upvotes: 2

jpp
jpp

Reputation: 164843

Here is one way:

Black = (("Hans","100"),("Frank","20.5"))

res = sum(float(num) for name, num in Black)
# 120.5

Alternative method using zip:

res = sum(map(float, list(zip(*Black))[1]))
# 120.5

Upvotes: 0

Related Questions