bjornasm
bjornasm

Reputation: 2318

Why do I get a type error: float when I try to iterate my list

So I sorted out my slightly embarrassing blunder here: What is happening with my types, TypeError? (Python)

Now I got an other one.

My method for retrieving data:

def retrieveSpeeds(databasepath, someid):
     con = lite.connect(databasepath)
     with con:
        cur = con.execute("SELECT speed FROM speeds WHERE id = someid")
        speeds = [x[0] for x in cur]
        for i in range(0, len(speed)):
            newspeeds.append(float(speed[i]))
     return speeds

So the return looks like:

[14.0, 14.5, 14.5, 14.5, 14.5, 13.8]

In my main I do:

maxspeeds = []
for id in userid:
    speed = retrieveSpeeds(databasepath, id)
    if len(speed)>0:
           maxspeeds.append(max(speed))
for i in range(0,len(maxspeeds)):
    if maxspeeds[i] > 40:
          maxspeeds = maxspeeds.pop(i)

Now my new problem is:

    Traceback (most recent call last):
    if maxspeeds[i]>40:
    TypeError: 'float' object has no attribute '__getitem__'

How is it that it suddenly thinks that my list is a float object? More blunders from me?

Upvotes: 1

Views: 66

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

This line:

maxspeeds = maxspeeds.pop(i)

rebinds maxspeeds to the value of the expression maxspeeds.pop(i), which is a float.

Upvotes: 3

A.J. Uppal
A.J. Uppal

Reputation: 19264

You are assigning maxspeeds to the output of maxspeeds.pop(i) which returns a number, which is the index of the popped item. Instead, don't assign anything to the output:

maxspeeds = []
for id in userid:
    speed = retrieveSpeeds(databasepath, id)
    if len(speed)>0:
           maxspeeds.append(max(speed))
for i in range(0,len(maxspeeds)):
    if maxspeeds[i] > 40:
          maxspeeds.pop(i) #Here

.pop returns the index of the deleted item, so when you assign the list to that output, the list becomes the index (an integer).

Upvotes: 4

Related Questions