1

I'm trying to delete binary numbers from a list that don't contain the number of zeroes a user enters.

a = []

for i in range(512):
    a.append(format(i, '09b'))

b = int(input("Enter zeroes: "))

for i in a:
    if i.count('0') != b:
        del(i)

for i in a:
    print(i)

But running this code still yields the full list of 9 bit numbers. Where am I going wrong?

eddiewastaken
  • 822
  • 8
  • 23

1 Answers1

0

You need to use a.pop in order to delete something from the list.

However, you'd be much better off simply recreating the list, like this:

new_a = [i for i in a if i.count('0') == b]

It's more functional, and more clearly expresses what you're trying to do. It's also possibly more efficient. Deleting items randomly from a list is a linear operation. If you do it n times, you might end up with a quadratic algorithm. Rebuilding the list is only linear.

Horia Coman
  • 8,681
  • 2
  • 23
  • 25