Skip to content Skip to sidebar Skip to footer

Adding Integers Progressively To A List

It's a while loop and I need to add the log variable (most recent variable) to a list. I have no idea how to do it. I'm going to add every number that is a multiple of both 5 and 7

Solution 1:

If you are looking for efficiency, do some math first:

  1. 5 and 7 are primes to themselves so a number is divisible from both if and only if it is divisible from their product.
  2. After finding the first number that satisfies point 1, simply keep adding 35 until you reach the end of your range. Note that you know how many such numbers will be in your range!

Now the code:

first = next(x for x in range(1500, 2701, 5) if x % 35 == 0)
res = [first + 35*i for i in range((2701-1-1500)//35 + 1)]

which produces:

[1505, 1540, 1575, 1610, 1645, 1680, 1715, 1750, 1785, 1820, 1855, 1890, 1925, 1960, 1995, 2030, 
 2065, 2100, 2135, 2170, 2205, 2240, 2275, 2310, 2345, 2380, 2415, 2450, 2485, 2520, 2555, 2590, 
 2625, 2660, 2695]

This will be faster than any if-based approach.


As far as the problem with your code goes, it has been thoroughly discussed by the other answers and comments, so I will not go into that.


and in general but that is irrelevant here

Solution 2:

You don't need to increment x when you have met a condition, as that's handled for you by the range generator.

You are close:

somelist = []

for x inrange(1500, 2701):
    if x%5==0and x%7==0:
        somelist.append(x)
    # You don't need an else block as the loop will just continue

You could alternatively do this in a list comprehension for more speed:

somelist = [x for x inrange(1500, 2701) if x%5==0and x%7==0]

Solution 3:

result =[]    
for x in range(1500,2701):
        if x % 7==0 and x % 5==0:
            result.append(x)    
        else:
            print(x,"is not a common factor")
            x=x+1

Solution 4:

Create a list variable:

foo_list = []

After that, all you need to do is at the end of your loop append the value to your list

foo_list.append(<your variable>)

So it would look something like this on your code:

my_list = []
x=1500for x in range(1500,2701):
    if x % 7==0 and x % 5==0:
        print("\n", x,"IS DIVISIBLE\n")
        my_list.append(x)
    else:
        print(x,"is not a common factor")

As you can see, the x+=1 was deleted, the loop is doing it for you!

As some people pointed out, if you are just interested in getting the list and not printing wether if the number is a common factor or not you could use list comprehensions, as follows:

my_list= [x for x in range(1500, 2701) if x%5==0 and x%7==0]

Solution 5:

my_list = []
for x in range(1500,2701):
    if x % 7==0 and x % 5==0:
        print("\n", x,"IS DIVISIBLE\n")
        my_list.append(x)
            #I THINK THE LIST STUFF GOES HERE


    else:
        print(x,"is not a common factor")
print(my_list)

Post a Comment for "Adding Integers Progressively To A List"