2

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.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
heppen
  • 23
  • 4
  • 2
    Closely related: [Reassigning value of iterator while iterating through it](//stackoverflow.com/a/53116048) – Aran-Fey Jun 17 '19 at 11:21

2 Answers2

0

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.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
  • Thanks, I wanna know why use `nums.extend()` can change nums' value in for loop, but `=` can't. Is variable left at `=` a new variable, but `nums.extend()` is the old value? Sorry for my poor English⊙﹏⊙ – heppen Jun 18 '19 at 01:15
  • @heppen A simplified explanation. When the loop starts, it will use whatever list was specified at the beginning. That list is an "object". You need to modify _that_ object and the loop will be "aware" of those changes. However, you were creating a new list object and simply naming as `nums` does not modify the _original_ object. The following may be helpful: https://stackoverflow.com/q/6793872/8033585. Also, try the following exercise: `a=[1,2]; b=a; a=[1,2]; a.append(3); print(a); print(b)`. – AGN Gazer Jun 18 '19 at 02:18
  • @heppen Finally learn about `is` and `id()` in Python, i.e., https://stackoverflow.com/q/13650293/8033585 and try adding `print(id(nums))` after each `nums = ...` in your original code. – AGN Gazer Jun 18 '19 at 02:19
0

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

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • Thanks a lot, but I think your code just use `if` to reduce `count` value, but the `for` still repeat 9 times. What I want is to reduce `for` loop times. – heppen Jun 18 '19 at 01:22