FlyingBurger
FlyingBurger

Reputation: 1372

how to solve TypeError: 'float' object is not iterable

How can I transfer

A = [0.12075357905088335, -0.192198145631724, 0.9455373400335009, -0.6811922263715244, 0.7683786941009969, 0.033112227984689206, -0.3812622359989405] 

to

A = [[0.12075357905088335], [-0.192198145631724], [0.9455373400335009], [-0.6811922263715244], [0.7683786941009969], [0.033112227984689206], [-0.3812622359989405]]

I tried to the code below but an error occurred:

new = []
for i in A:
    new.append.list(i)

TypeError: 'float' object is not iterable

Could anyone help me?

Upvotes: 8

Views: 113103

Answers (4)

Aryan Daftari
Aryan Daftari

Reputation: 11

I think you are using like that:

my_data=b['dataset']['data'][0][1]
useful_data=[i[1] for i in my_data]

So when you compile it gives you an error:

TypeError: 'float' object is not iterable

Try only:

my_data=b['dataset']['data']

Then you will get your data.

Upvotes: 1

Ivan Vinogradov
Ivan Vinogradov

Reputation: 4473

tl;dr

Try list comprehension, it is much more convenient:

new = [[i] for i in A]

Explanation

You are getting TypeError because you cannot apply list() function to value of type float. This function takes an iterable as a parameter and float is not an iterable.

Another mistake is that you are using new.append._something instead of new.append(_something): append is a method of a list object, so you should provide an item to add as a parameter.

Upvotes: 20

jpp
jpp

Reputation: 164643

list.append is a method which requires an argument, e.g. new.append(i) or, in this case new.append([i]).

A list comprehension is a better idea, see @IvanVinogradov's solution.

If you are happy using a 3rd party library, consider numpy for a vectorised solution:

import numpy as np

A = [0.12075357905088335, -0.192198145631724, 0.9455373400335009, -0.6811922263715244, 0.7683786941009969, 0.033112227984689206, -0.3812622359989405] 

A = np.array(A)[:, None]

print(A)

# [[ 0.12075358]
#  [-0.19219815]
#  [ 0.94553734]
#  [-0.68119223]
#  [ 0.76837869]
#  [ 0.03311223]
#  [-0.38126224]]

Upvotes: 1

stasdeep
stasdeep

Reputation: 3138

You have a mistake, try:

new = []
for i in A:
    new.append([i])

Here is more beautiful solution:

new = [[i] for i in A]

Upvotes: 3

Related Questions