How to modify the sequence(not range) in the for loop?

Viewed 183

I just want to get a prime number list, but I find that the for loops more times than I image, it seems that the sequence don't change even though I modified the variable with the same name.

I try name nums as global, but nothing changed.

nums = list(range(2, 11))
count = 0
for num in nums:
    nums = list(filter(lambda a: a == num or a % num, nums))
    count += 1
print(count)  # 9
print(nums)

I want nums = list... can modify nums in for num in nums, and the count is 4. Thank you.

2 Answers

Without understanding exactly why you want to do what you want to do and whether it is necessary or avoidable, here is a solution that might do what you want:

nums = list(range(2, 11))
count = 0
for num in nums:
    new_nums = list(filter(lambda a: a == num or a % num, nums))
    del nums[:]
    nums.extend(new_nums)
    count += 1
print(count)  # 4
print(nums)

Your original implementation was creating a new variable called with the old name nums. However, it was a new variable/memory object of which the loop was not aware. The proposed solution keeps the original object and modifies it by first deleting all existing elements and then adding all new elements of the list.

Does this solve your problem?

nums = list(range(2, 11))

def f(num, nums):
    return list(filter(lambda a: a == num or a % num, nums))

count = 0
for i in range(len(nums)):
    if i < len(nums):
        nums = f(nums[i], nums)
        count+=1
print(nums)
print(count)

[2,3,5,7]

4

Related