-3

I have such a list:

for i in [100, 1000, 10000]:
    print(i)

How could I reproduce it with range

for i in range(100, 10000, 100)
    print(i)

the above code does not work as expected.

user10726006
  • 265
  • 4
  • 7

3 Answers3

9

You are printing increasing powers of ten, so you can do this:

>>> for i in range(2, 5):
...     print(pow(10, i))
... 
100
1000
10000

Edit

As Graham observes in the comments, you can also do

>>> for i in range(2, 5):
...     print(10 ** i)
... 
100
1000
10000

if you prefer the ** notation for exponentiation.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • For other readers, note also that exponentiation can be done in python using the `**` operator. So the 2nd line could be rewritten as `print(10 ** i)`, where `a ** b` is "a to the power b". – Graham Dec 16 '18 at 13:10
  • This is a good solution but I prefer the@Nils Werner solution's. – R. García Dec 16 '18 at 13:10
  • @Graham That's a good point; when writing I thought `pow()` was faster than `**`, but apparently they [perform similarly](https://stackoverflow.com/a/48848512/5320906), whereas `math.pow` is slower. – snakecharmerb Dec 16 '18 at 13:14
  • @snakecharmerb it says `math.pow` is faster. Am I reading it wrong? – Aykhan Hagverdili May 10 '20 at 22:53
  • 1
    @Ayxan you're quite right, that answer says that `math,pow` is "often faster", but potentially less precise. Thanks for noticing. – snakecharmerb May 11 '20 at 06:57
4

With a single line:

print(*(10 ** n for n in range(2, 5)), sep='\n')

Not the * operator, which is used to unpack the tuple. The ** finds powers of 10, and sep denotes the string which is put between elements print outputs.

As @Walter notes in the comments, this method is not particularly efficient for larger ranges. @snakecharmerb's method with a for loop is the recommenced choice in those cases.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
2

There are a couple of options

import numpy as np
for i in np.logspace(2, 4, num = 3, endpoint = True, dtype = np.int):
    print(i)

or (edit based on @Graham comment)

for i in (10**k for k in range(2, 5)):
    print(i)
caverac
  • 1,505
  • 2
  • 12
  • 17
  • 1
    you shouldn't presume that everyone knows what you mean by `np` – Walter Tross Dec 16 '18 at 13:10
  • In the second case, there's absolutely no point in making it a list using the `[` and `]`; it's simply not optimally memory efficient for large ranges, and therefore a bad practice. Instead, you should make it a generator expression using parentheses: `(10**k for k in range(2, 5))` – Graham Dec 18 '18 at 12:20