Get a list of the first multiples of a number

Asked

Viewed 342 times

0

I need to do a program that determines the first 5 multiples of 3, and I wanted to put the values of the first 5 numbers into a variable, but I don’t know how to do that. I tried to make:

for index in lista:
    while 1 <= index <=5:
        numeros.append(lista[index])
        index == index +1

But that didn’t work. I also tried:

numeros = []
lista = []
for n in range(1, 100):
    if n % 3 == 0:
        lista.append(n)
        print(lista)
  • 2

    It wouldn’t just be something like lista = [3*1, 3*2, 3*3, 3*4, 3*5]?

6 answers

2

To have the first multiples of 3, just create a list with the result of 3 * 1, 3 * 2, 3 * 3, etc., until 3 * N.

Then it is enough that the range go from 1 to N, and you enter the result of the multiplication of 3 by each element of the range:

n = 5 # quantidade de múltiplos
multiplos = []
for i in range(1, n + 1):
    multiplos.append(3 * i)
print(multiplos)

Remembering that in a range the final value is not included, so I put n + 1, so that he can go to the umpteenth multiple.

Another option is to use one comprehensilist on, much more succinct and pythonic:

n = 5 # quantidade de múltiplos
multiplos = [ 3 * i for i in range(1, n + 1) ]
print(multiplos)

Or, using map to map each value of the range for your triple:

n = 5 # quantidade de múltiplos
multiplos = list(map(lambda i: i * 3, range(1, n + 1)))
print(multiplos)

Finally, you can also generate the range with the multiples themselves. Just start at 3 (which is the first multiple), end at 3 * N (the umpteenth multiple), and skip 3 by 3 (to always get the next multiple). Then just get the list directly from it:

n = 5 # quantidade de múltiplos
multiplos = list(range(3, (n * 3) + 1, 3))
#                      ^   ^^^^^^^^^^  ^
#                      |       |       |
#                      |       |       \__ passo (pular de 3 em 3)
#                      |       |
#      valor inicial __/       \__ valor final

print(multiplos)

1

From what I understand you want to implement a script that can find and list the 5 first multiples of 3. Well, to solve this problem we can use the following code:

lista = list()
for i in range(3, (5 * 3) + 1, 3):
    lista.append(i)

print(lista)

Note that the for is traversing the range that starts in the minor multiple of 3 - which is 3 - going up to the fifth multiple of 3 - which is 15 - with step 3.

Or if you prefer, you can use the List Comprehensions.

lista = [i for i in range(3, (5 * 3) + 1, 3)]
print(lista)
  • thanks ! as I am still very new with Python I still have problems to imagine different ways to solve the same problem. Thanks for the help!

1

You can also do using the module itertools that has some interesting functions to work with iterators.

Python iterators are simply objects that can be traversed one element at a time. For this, they implement the Iteration protocol.
Here it is interesting only to know that the crossing of the elements of an iterator is done by the built-in method next() which retrieves the next iterator item.

The module itertools houses the function itertools.count(start= 0, step= 1) which creates an iterator that returns uniformly spaced values starting with start and spaced by step. As an example the expression:

count(n,n)

It is the expression python for all multiples of a number n going from n to infinity.

Putting in a generic example:

from itertools import count                          #Importa para o código o método count().

n = int(input('Digite o número:'))                   #Lê o número que será gerada a tabuada de múltiplos.
m = int(input('Digite a quantidade de múltiplos:'))  #Lê o número de múltiplos a serem gerados na tabuada.

i = count(n,n)                                       #Cria o iterador para o múltiplos de n.

for _ in range(m):                                   #Para os primeiros m múltiplos de n...
    print(next(i))                                   #...os imprime.

Testing:

Digite o número:3
Digite a quantidade de múltiplos:5
3
6
9
12
15

Digite o número:6
Digite a quantidade de múltiplos:20
6
12
18
24
30
36
42
48
54
60
66
72
78
84
90
96
102
108
114
120

Also, as suggested in comments by users hkotsubo and Woss, it is possible to use the function isocup() that returns a lot of elements from an iterable:

from itertools import count, islice
 
n = int(input('Digite o número:'))                   
m = int(input('Digite a quantidade de múltiplos:')) 

print(list(islice(count(n, n), m)))

Testing:

Digite o número:3
Digite a quantidade de múltiplos:5
[3, 6, 9, 12, 15]
  • 2

    A suggestion with itertools: https://ideone.com/AddTZ8

  • 1

    @hkotsubo: Thanks after lunch I will put in response.

  • 2

    I: "I will comment that you can use the islice to get the N values... ih, already have a suggestion from @hkotsubo, want to see which is using the islice?" hahaha

0

Your code is working. But there is a more practical way to do it:

lista = []
for n in range(3, 100, 3):
    lista.append(n)
print(lista)

This way you already jump 3 by 3, without having to make checks of rest.

  • well thought!! I had not thought of this option to put the loop to jump 3 in 3... thanks

0

This solution solves your problem, a list is created to store multiples of three lista_multiplos = [], the value num is constant, so a for multiplies num by five elements for n in range(1, 6):. soon after is displayed the multiples in the loop below the first. I hope it helps :)

num = 3
lista_multiplos = []
for n in range(1, 6):
    lista_multiplos.append(num*n)
for elemento in lista_multiplos:
    print(elemento)

0

Although they suggested answers with more practical ways to accomplish the proposal, I thought it would be worth clarifying some points that you might be getting confused with iterations in lists.

When using the operator for x in y the variable x will not take the index of the element in the list y, and yes, the value of the element itself.

frutas = ["Maçã", "Banana", "Uva"]

for fruta in frutas:
    # Isso ira exibir os nomes das frutas
    # A variável "fruta" assume o valor do elemento na lista
    print(fruta)

If you want to work with the index of each element, an alternative is to use the operator enumerate

frutas = ["Maçã", "Banana", "Uva"]

for indice, fruta in enumerate(frutas):
    # Agora você consegue trabalhar com os dois
    # Tanto índice quanto valor do elemento
    print(str(indice) + " = " + fruta)

Another option would still be to perform an iteration with a range from 0 to the size of your list, which even does not need to be known, you can get the list size with the operator len

frutas = ["Maçã", "Banana", "Uva"]

for indice in range(len(frutas)):
    # Assim voce também consegue trabalhar com o indice e valor
    print(str(indice) + " = " + fruta)
  • po valeu msm guy... I’m still new in this world and I’m catching a little kkkk but thanks for the clarification

Browser other questions tagged

You are not signed in. Login or sign up in order to post.