0

Suppose, i have a list that has range from 1 to 50. I need to remove all the integers(elements) with factor f (user input) from the list. For example, if = 2, the program should remove 4, 6, 8, 10, … from the sequence of integers and print the remaining number of integers in the sequence. Functions() such as remove() or any other functions are not allowed for this exercise. I'm still learning.

Edit: I'm not allowed to use enumerate(), slicing, list comprehension. Sorry. If there's a better way of getting output than mine, I'm open to it.

lis = [1, 2, 3, 4, 5........51]

while True:
    f = int(input())
    if f == 0:
        break

    for i in lis:
        if (i % f == 0 and i != f):
            lis.remove(i)........#i cant figure how to remove without using remove()
    c = len(lis)
    print('Number of remaining integers:', c)
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • If you are allowed to create a new list that is the cleanest way for me, add the valid elements and skip the others (use a list [comprehension](https://stackoverflow.com/a/1207461/2237151) for that). As a side note, be aware that iterating using `for i in lis` and removing elements is generally a bad idea, as the loop will fail. – Pietro Apr 04 '21 at 13:11

2 Answers2

2

There are few ways of doing that without using remove.

The first one is creating a new list and append to it all numbers which you want to save and ignore the other ones:

lis = [1, 2, 3, 4, 5........50]
new_lis = []

while True:
    f = int(input())
    for num in lis:
        if not (num  % f == 0 and num  != f):
           new_lis.append(num)
    lis = new_lis
    c = len(lis)
    print('Number of remaining integers:', c)

The second solution is to nullify the numbers in the list and then iterate on it again and return the new one with list comprehension:

lis = [1, 2, 3, 4, 5........50]

while True:
    f = int(input())
    for idx, num in enumerate(lis):
        if (num % f == 0 and num != f):
            lis[idx] = None
    lis = [n for n in lis if n is not None]
    c = len(lis)
    print('Number of remaining integers:', c)

In both solutions, i recommend change lis to be l, usually partial naming is not giving a special value and less recommended.

Hook
  • 355
  • 1
  • 7
0

This is how i would do it :

lis = [1, 2, 3, 4, 5........50]

while True:
   f = int(input())
   if f == 0:
      break

   new_lis = [item for item in lis if item == f or item % f != 0]

   print('Number of remaining integers:', len(new_lis))

Any time you have a for loop appending items to a list, and the list starts off empty - you might well have a list comprehension.

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33