Home > front end >  Python: cannot get floating numbers in list
Python: cannot get floating numbers in list

Time:05-05

I made a simple loop for which the input is a list of integer numbers. These numbers are then subjected to some random mathematical operations. What I want is that it outputs another list with the (floating point) results, but I cannot seem to make it work. Using 'append' gives me an error saying that the floating point numbers are not iterable. I don't really know how I could put these floats in a list otherwise... Could someone steer me into the right direction? I included the coding in the following printscreen .

1

#What works, but result is non-listed floats
xlst = range(1, 100)
print(list(xlst))

ylst = []
res = []

for i in xlst:
    res = i * 1.1
    print(res)

#How I thought I could list everything, but floats are not iterable

#for i in xlst:
    #res = res.append(i * 1.1)
    #print(res)

CodePudding user response:

Your attempt is in the good direction but here are a few hints:

  • the value of res is not set back to res = [] before the loop on line 14. Therefore, its value was last set by line 9. res is thus a float and res.append() will logically fail on AttributeError: 'float' object has no attribute 'append'.
  • line 15 sets res with the output of res.append(). However, in python, append adds the element in place and returns None and not the extended sequence as you seem to be expecting.
  • line 16 will be executed for each step of your line 14 loop. To only display the full list once completed, you should move it out of the loop (by decrementing it).

Gathering all the above hints gives this final result to replace line 14 onwards:

res = []
for i in xlst:
    res.append(i * 1.1)
print(res)

Hope this makes things clearer!

CodePudding user response:

Use a list comprehension.

res = [x * 1.1 for x in xlst]

CodePudding user response:

res = [] # after assignation res is a list object

for i in xlist:
    res = i * 1.1 # after assignation res is a float number
    print(rest)

After the 1st iteration of that for loop, var res will be a float object, also after the whole loop, so in the commented code, you cant do append, because float objects aren't lists. Even deleting the first for loop you will get a similar error, because list.append() returns None:

res = res.append(i * 1.1) # after assignation res is None

Solution: A simple for as follow:

res = [] # after assignation res is a list object

for i in xlist:
    aux = i * 1.1 # using an auxiliary float var
    print(aux)
    res.append(aux) # storing in the list
  • Related