0

I am doing one of the Python beginner projects in this subreddit: http://www.reddit.com/r/beginnerprojects and for part of one of the tasks, I need to remove all integers from this list that have less than two digits. I'm not sure where I'm going wrong. I know I could just change the range in the list, but I want to utilise as many skills as possible.

numbers = [x for x in range(1,1001)]

def two_or_more_digits():
    for num in numbers:
        if len(str(num)) < 2:
            numbers.remove(num)
    print (numbers)

I am working in Python 3.

Thank you.

billylevin
  • 82
  • 2
  • 8
  • Hi! Are you calling the two_or_more_digits function? It doesn't show in your code – mguijarr Aug 16 '14 at 14:27
  • possible duplicate of [Removing Item From List - during iteration - what's wrong with this idiom?](http://stackoverflow.com/questions/2896752/removing-item-from-list-during-iteration-whats-wrong-with-this-idiom) – bereal Aug 16 '14 at 14:29
  • Yes, I am. Sorry, forgot to put that in. The print should also be indented 4 spaces. I'll edit that now. – billylevin Aug 16 '14 at 14:30
  • 1
    For the `range(1, 1001)` you're iterating over - why convert to `str` then take the `len` - a much more simple test is to check that it's `>= 10`... (in fact - `range(10, 1001)` will give you the result you're after from the outset...) – Jon Clements Aug 16 '14 at 14:31
  • can numbers contain any combination of different numbers in any order? – Padraic Cunningham Aug 16 '14 at 14:50
  • in your own code if you use `for num in numbers[:]` you will also get the desired result, it makes a copy of numbers to iterate over, then you are not iterating over and mutating the same list which is something you should not do – Padraic Cunningham Aug 16 '14 at 16:55

3 Answers3

1

Instead of converting your digit to a string and calculating its length you can also use simple division:

[i for i in range(1,1001) if i // 10 > 0]

this will return a list with ints from 10 to 1000 (inclusive).

martin
  • 676
  • 4
  • 9
0

You can use list comprehension:

numbers = [x for x in range(1,1001) if len(str(x)) >= 2]

Or filter:

all_nums = [x for x in range(1,1001)]
needed_nums = filter(lambda i: len(str(i)) >= 2, all_nums]

If all elements all integer, you don't need to convert it to str and filter by length, you can just use x >= 10 instead of len(str(x)) >= 2

WKPlus
  • 6,955
  • 2
  • 35
  • 53
0

You're altering the numbers array while iterating over it... Can that be right?

If you want to grow your skills, probably you want to express the condition as a predicate, and use it either in a filter, or in a list comprehension:

filtered = filter( lambda x: len(str(num)) < 2, numbers )

filtered2 = [x for x in numbers if len(str(x)) < 2]

(or even better: use itertools.ifilter instead)

xtofl
  • 40,723
  • 12
  • 105
  • 192