Reputation: 185
I have these lists:
sqvaluelist = []
valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]
I want to apply this code on the valuelist:
for value in valuelist:
valuesquared = value*value
sqvaluelist.append(valuesquared,)
but I received this error:
TypeError: can't multiply sequence by non-int of type 'tuple'
I think I know the reason behind this error, it is because every value is inside a separate tuple.
My question is, is there any way to take this values off their respective tuple, and just turn them into a list like
valuelist = [10.5, 20.5, 21.5, 70.0, 34.5]
without manually editing the structure of the existing list so that the for loop can be executed?
EDIT: I apologize! They are actually tuples! Added commas after each value. Sorry!
Upvotes: 0
Views: 1870
Reputation: 287
Doing it in pythonic way:
sqvaluelist = [v[0]**2 for v in valuelist]
Upvotes: 1
Reputation: 8370
To make
valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]
into
valuelist = [10.5, 20.5, 21.5, 70.0, 34.5]
I'd use list comprehension
valuelist = [x[0] for x in valuelist]
Upvotes: 6
Reputation: 41428
Yes you can do so very easily in a one liner :
map(lambda x: x, valuelist)
This works because as @eumiro noted, (10.5) is actually a float and not a tuple. Tuple would be (10.5,).
To compute the squares it's as easy:
map(lambda x: x*x, valuelist)
If you have a list of real tuples like (10.5,), you can modify it like this:
map(lambda x: x[0], valuelist)
map(lambda x: x[0]*x[0], valuelist)
Upvotes: 1
Reputation: 336138
Just access the first element of each tuple:
>>> valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]
>>> sqvaluelist = [x[0]*x[0] for x in valuelist]
>>> sqvaluelist
[110.25, 420.25, 462.25, 4900.0, 1190.25]
Upvotes: 1
Reputation: 212875
valuelist = [(10.5), (20.5), (21.5), (70.0), (34.5)]
is a list of ints:
>>> [(10.5), (20.5), (21.5), (70.0), (34.5)]
[10.5, 20.5, 21.5, 70.0, 34.5]
(10.5)
is an integer. (10.5,)
is a tuple of one integer.
Therefore:
>>> sqvaluelist = [x*x for x in valuelist]
>>> sqvaluelist
[110.25, 420.25, 462.25, 4900.0, 1190.25]
Upvotes: 3