Can someone explain the range | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone explain the range

2nd Nov 2016, 9:42 AM
code-junkie
code-junkie - avatar
4 Answers
+ 6
range(y) gives you a list with numbers from 0 to y not included. range(x, y) gives you a list with numbers from x to y not included. range(x, y, z) gives you a list with numbers from x to y not included with a step of z (ie you get x, x+z, x+2z, etc.). For example: range(3) gives you [0, 1, 2]. range(1, 3) gives you [1, 2]. range(1, 6, 2) gives you [1, 3, 5].
2nd Nov 2016, 10:10 AM
Zen
Zen - avatar
+ 1
to make it easy to understand here's my example for range (10) it will count from 0-9 (10 numbers) for range (5,10) it will start at 5 ,6,7,8,9 (last num always not included) for range(1,10,2) 1 =num to start 10=end of count 2 = num. it counts so the result would be 1,3,5,7,9
4th Nov 2016, 4:00 PM
HeliuM Lee
HeliuM Lee - avatar
0
Allow me to add some more technical stuff about range(). In Python 3.x the range() function returns an iterator (xrange() in Python 2). This means that in - for example - a for loop the range() produces/yields the consecutive numbers on the fly. The old range() in Python 2 returns the whole list before the execution of an e.g. for loop. This is faster for small loops, but returning a huge list for very large loops can cause memory problems. This is solved with the xrange() (or simply range() in Python 3.x) by yielding the next number in each loop. Now returning an iterator means that you can't print or save a list of numbers out of it directly. If you want the list out of a range() you can simply do: my_list = list(range(100))
3rd Nov 2016, 9:32 AM
Anastasios Glaros
Anastasios Glaros - avatar
0
result 8
15th Dec 2022, 6:07 PM
sajad heydari
sajad heydari - avatar