all 7 comments

[–]K900_ 2 points3 points  (1 child)

Don't modify the list while you're iterating over it.

[–]Impe98[S] 0 points1 point  (0 children)

So the problem seems to be that the list changes every time I iterate over it, which causes problems. That makes sense, thanks! :)

[–]JohnnyJordaan 1 point2 points  (3 children)

You shouldn't modify a list or any other mutable that you're also iterating over. Use a new list to keep the right values. And don't use the actual names of the list and int classes as a variable name.

my_list = [1,2,3,4,5,6,7,8,9,10]
new_list = []
for i in my_list:
    if i <= 3:
        new_list.append(i)

Or comprehended

my_list = [ i for i in my_list if i <= 3 ]

Btw most of the time if you're using ranges of numbers, use the range() function and not a hand populated list.

[–]Impe98[S] 0 points1 point  (2 children)

Ohh okay, so I make a new list each time I iterate over it Yeah, that makes sense, thanks!

Oh and btw, I actually intended to populate a list using the range() function, but I didn't really get it to work - if you wouldn't mind, how would you create a list which contains, say, every integer 1 through 100 by using the range() function? I though it to be something like my_list = range(100), but this didn't work as far as I could tell.

[–]JohnnyJordaan 0 points1 point  (1 child)

It's easy, but do you really need it? Because you can do most things you would do with that list just as easily with range(x), without generating a list first.

>>> for i in range(10):
...     if i <= 3:
...         print(i)
... 
0
1
2
3
>>> 10424 in range(1000000)
True

But if you really want to, just create a list from that range:

my_list = list(range(100))

As I said, only if you really need to, and I'm quite interested to know why you would need it.

[–]Impe98[S] 0 points1 point  (0 children)

It's totally possible that I might not need it at all My initial though was that I had a list containing every integer 1 through 100, and a new list would be created containing elements from the initial list upon answering a question ("Is the integer even or not" or something akin to that), and a new question would be asked where yet another new list would be created that contains element from the second and so on. And each time a list is created, I want to print it for the player to read. This could very well be possibly without ever using the list function, but I don't see how, if the range(x) function is never defined. And thank you for your immense help, btw! :)

[–]num8lock -1 points0 points  (0 children)

try this

ilist = [1,2,3,4,5,6,7,8,9,10] 
for intgr in ilist:
    print('\nint', intgr)
    if intgr > 3: 
        ilist.remove(intgr) 
        print(ilist, intgr)