Multiplying a list by any constant c
will repeat the elements in the list by a c
number of times.
To better understand what's going on here, you should start by multiplying the list by a smaller constant and eventually work your way up to 157. Let's start by multiplying the list by 1:
products = numbers*1
print(products)
[42, 4224, 42422424, -250]
We can see that multiplying the list by 1 will just send us back our original list, since the elements are only included once in the list. Next, we'll multiply the list by 2:
products = numbers*2
print(products)
[42, 4224, 42422424, -250, 42, 4224, 42422424, -250]
We can see that the elements are repeated twice in the same list. You can increase the constant on your own to observe the increased amount of repetition.
As others have suggested, you can simply use either list comprehension or numpy arrays to retrieve your desired output:
Method 1: List Comprehension
products = [i*157 for i in numbers]
print(products)
[6594, 663168, 6660320568, -39250]
List comprehension is essentially shorthand for writing a loop that multiplies each individual element by 157, in our situation.
Method 2: Numpy Arrays
products = np.array(numbers)*157
print(products)
array([6594, 663168, 6660320568, -39250])
Numpy is a module used for array-processing and data manipulation. You can read more about the benefits of numpy here.
Performance Testing
I'll include some performance differences below. This is also a good example that includes multiplying a list by a constant and multiplying its elements by a constant.
>>> timeit.timeit('[i*157 for i in numbers]', 'numbers=[42, 4224, 42422424, -250]', number=1000000)
0.35015837100013414
>>> timeit.timeit('numbers*157', 'import numpy as np;numbers=np.array([42, 4224, 42422424,-250])', number=1000000)
0.639420188000031
>>> timeit.timeit('[i*157 for i in numbers]', 'numbers=[42, 4224, 42422424,-250]*500', number=1000000)
91.96342155899993
>>> timeit.timeit('numbers*157', 'import numpy as np;numbers=np.array([42, 4224, 42422424,-250]*500)', number=1000000)
1.3476544480001849
Typically, numpy arrays are known to perform better than ordinary Python lists for larger array-like data. However, there are certain instances where Python lists can perform better than numpy arrays, which you can read more about here.