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) 
1
  • 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 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. Commented Apr 4, 2021 at 13:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

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.