PDA

View Full Version : Python - Print numbers without making a list?



dodle
March 23rd, 2009, 07:48 AM
In python, if I wanted to print a list of numbers I could make a list then print it:
list = [1,2,3,4,5,6,7,8,9,10]
print listor:
list = [1,2,3,4,5,6,7,8,9,10]
for num in list:
print numBut if I wanted to print out the numbers 1-10 without making a list, how would I do it?

ghostdog74
March 23rd, 2009, 08:03 AM
range()

lswest
March 23rd, 2009, 08:07 AM
Yeah, you could just do that with:


for x in range(1,11):
print x


Range is a function that reads from one position up to (but not including) the last position specified in the function (thus 1,11=1-10)

dodle
March 23rd, 2009, 08:14 AM
Thank you, very helpful.

ghostdog74
March 23rd, 2009, 09:07 AM
Yeah, you could just do that with:


for x in range(1,11):
print x

for the sole purpose of just printing a range out, just print range(1,11) will do. No need for a loop.

lswest
March 23rd, 2009, 01:13 PM
for the sole purpose of just printing a range out, just print range(1,11) will do. No need for a loop.

Always useful to know (I've not been doing python for all too long), thanks for the info.

wmcbrine
March 24th, 2009, 04:47 AM
In Python 2.x, range() returns a list, so technically it doesn't fulfill the OP's stated requirement of "without making a list" (although it does what he really wanted). But xrange() returns an iterator, so it does.

In Python 3.x, xrange() becomes range(), and the old range() is dead.