0
a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
b = []

for i in range(a):
    if a[i] == 0.00:
        b.append(0)
    else:
        b.append(1)

What I want is to fill b with 0 and 1 according to if the same index in a is equal to or different from zero. Why am I getting the following error: "TypeError: 'list' object cannot be interpreted as an integer"?

1
  • Mandatory warning: Checking for equality for floating-point numbers are most likely wrong due to the imprecision of floating-point numbers. Check with a small epsilon instead. Commented May 28, 2021 at 16:16

5 Answers 5

7

range() takes only integers (start:stop:step). Not a list. So I think you want to use len(list)

a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
b = []

for i in range(len(a)):
    if a[i] == 0.00:
        b.append(0)
    else:
        b.append(1)

Lastly, all this can be done using list comprehension

#Note: when iterating through a list, don't use range()

b = [i if i == 0.00 else 1 for i in [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]]

output

[1, 1, 0.0, 1, 1, 0.0]
Sign up to request clarification or add additional context in comments.

3 Comments

While it works in this case, there should be a huge warning specifying that checking for equality between floats are often not correct due to imprecision of floating-point numbers.
That's true. So what would be an alternative @TedKleinBergman?
You should generally be checking against a small epsilon
3

The bug has already been covered in the other answers. Here's an alternative implementation:

>>> a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
>>> b = [int(bool(x)) for x in a]
>>> b
[1, 1, 0, 1, 1, 0]

Comments

2

As others have said, range takes an integer, not a list. But since no one is covering the biggest flaw in the code, here's a useful warning:

Checking for equality between floating-point numbers are most likely wrong due to the imprecision of floating-point numbers!

As an example, 0.1 + 0.2 == 0.3 is False. Just try it yourself. Instead, check with a small epsilon.

EPSILON = 0.0001
a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
b = []

for i in range(len(a)):
    if -EPSILON <= a[i] && a[i] <= EPSILON:
        b.append(0)
    else:
        b.append(1)

Or use a list comprehension, or any other technique used in the other answers.

Comments

1

First of all, as @BuddyBob said, range takes an integer, so that way won't work. Second, I am assuming that you want to loop through the items in a, so it would be easier to use for i in a: like this.

a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
b = []

for i in a:
    if i == 0.00:
        b.append(0)
    else:
        b.append(1)

Comments

1

You don't need to use range in your given example. You can just loop through list items:

a = [0.30, 0.15, 0.0, 0.25, 0.30, 0.0]
b = []

for i in a:
    b.append(0 if i == 0 else 1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.