r/PythonLearning • • 22h ago

i am stuck with the range function

sorry but i am gonna crash out because of the range function i cant understand it well to use it this is driving me crazy any one could give me a video explaining everything i dont mind it being an hour long

6 Upvotes

32 comments sorted by

4

u/ninhaomah 22h ago

What is it about range() function that driving you mad ?

It's like saying my Bluetooth mouse is driving me mad...

It doesn't move ? Not detected ? Buttons not working ? Who knows ?

3

u/Repulsive-Song-1594 21h ago

Let me tell you what i was strugling with Its usually lists and range Lets say i have ni = [2,4,6,9,12] I wanted it to just do 2+4 then 4+6 extra And i was 30 min trying because i didnt want to use ai to see the code

1

u/ninhaomah 21h ago

???

what has this got to do with range ?

we are talking about this range() right ?

"The built-in range data type represents an immutable sequence of numbers, typically used for looping a specific number of times in for loops. It generates arithmetic progressions and is memory efficient as it computes the numbers lazily:"

https://realpython.com/ref/builtin-types/range/

Examples from the above site :

>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

>>> range(1, 10, 2)
range(1, 10, 2)
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]

1

u/Repulsive-Song-1594 21h ago

Couldnt i make it with range because the teacher said we can

3

u/ninhaomah 21h ago

I still don't know what is the question or issue you have or what your teacher asked to do with range.

Pls post the question here 

1

u/Repulsive-Song-1594 21h ago

I study statistique and lemme make it clear what did i want Lets say we have Xi = 1,2,3,4,5 Ni = 2,4,6,9,12 Ni↑ = 2,6,12,21,33 I just want to do the Ni↑ with range function

2

u/ninhaomah 20h ago

What has what you study got to do with this ?

And how is this even a programming or math/stats question ?

You have 2 groups of numbers and you want to somehow get a third group of numbers using those 2 groups.

No rules or logic ?

Imagine I ask you x = 1,2 and y= 38,67 and z=43,87 ... I want to make z. How ?

1

u/Repulsive-Song-1594 20h ago

Ni↑ is Ni just adding number up Like first 2 Second 2+4 = 6 Third 6+6 = 12 Fourth 12+9 = 21 Till the end

2

u/ninhaomah 20h ago edited 20h ago

Then where does Xi in your example comes in ?

If 2+4 = 6 then why not 6+4 = 10 ?

Why suddenly 6+6 ?

If 21 is because 12+9 then what happened to 15 which is 9+6 ?

1

u/Repulsive-Song-1594 13h ago

Maybe i missed calculating i was almost asleep writing that about xi i will use it later just not in this i care now about just the ni

3

u/tmtowtdi 19h ago

You do not get bonus points for using as few words as possible.

You're not stating your problem clearly, nobody understands what you're talking about. Take a breath and try to type out what you mean exactly. You're allowed to use punctuation, just be clear.

1

u/mountain-snowman 17h ago

You are having trouble using range for a specific scenario, right? Write the code without range (even static code is fine), post the code here and ask how to achieve the same using range? You will get your answer with explanation.

1

u/TJATAW 20h ago

The only way I am seeing range being useful in that would be range(len(Ni)).

range used that way would make it work for any length of Ni.

One more hint:

fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: "cherry"

1

u/Naive_Programmer_232 17h ago edited 17h ago

ahh i see ignore my other comment, you're talking about cumulative sums i believe.

from typing import TypeAlias, Any

Number: TypeAlias = int|float

# with 'range'  (iterative)
def rng_csum(arr: list[Number]) -> list[Number]:
    res=arr[:1]
    for i in range(1,len(arr)):
        res.append(res[-1]+arr[i])
    return res

# without range (iterative)
def reg_csum(arr: list[Number]) -> list[Number]:
    res=arr[:1]
    for n in arr[1:]:
        res.append(res[-1]+n)
    return res

# without range (recursive)
def rec_csum(arr: list[Number]) -> list[Number]:
    if len(arr)<=1:
       return arr
    res=rec_csum(arr[:-1])
    res.append(res[-1]+arr[-1])
    return res

# itertools.accumulate is another way 
from itertools import accumulate as proven_csum

# compares any number of position args for equivalency
def all_equal(*args: Any) -> bool:
    return all(args[0]==e for e in args)

def test() -> None:

    Ni=[2,4,6,9,12]

    # results
    r1=rng_csum(Ni)
    r2=reg_csum(Ni)
    r3=rec_csum(Ni)
    r4=list(proven_csum(Ni))

    assert all_equal(r1,r2,r3,r4), "failed test case"
    print("\npassed test case\n")
    print(f"Ni↑={r1})

test()

passed test case

Ni↑=[2, 6, 12, 21, 33]

hopefully that gives you some ways you could go about it. best of luck!

1

u/mountain-snowman 16h ago

I think what you want is:

Ni_arrow = [sum(Ni[:i+1]) for i in range(len(Ni))]

This is a test code and there are better ways to do it while using the range as shown.

1

u/arivictor 19h ago

you mean this?

numbers = [2, 4, 6, 8, 10, 12]

for i in range(len(numbers)):
    if i + 1 == len(numbers):
        break

    result = numbers[i] + numbers[i + 1] # e.g. 2 + 4
    print(f"{numbers[i]} + {numbers[i + 1]} = {result}")

output

2 + 4 = 6
4 + 6 = 10
6 + 8 = 14
8 + 10 = 18
10 + 12 = 22

1

u/Repulsive-Song-1594 12h ago
ni = [2, 4, 6, 9, 12]

running_total = ni[0]
print(f"start: {running_total}")

for i in range(1, len(ni)):
    prev = running_total
    running_total = running_total + ni[i]
    print(f"{ni[i]} + {prev} = {running_total}")

the ai i just asked now showed me this too but after i told him again he showed me the right code
thats the part of range combining it with other things thats its hard for me to understand

1

u/arivictor 9h ago
start = 2
stop = 20
step = 2
for i in range(start, stop, step):
    print(i)

range uses start, stop, step. start is the number you want to start with in your first loop. stop is when you want the loop to exit when i is equal to or greater. step is how many to increment each time.

  • loop 1: 2, then it adds step, and i becomes 4

  • loop 2: 4, then it adds step, and i becomes 6

  • ...

  • loop 9: 18, i becomes 20

  • exits: stop says 20, i is 20, so the loop does not run.

i

1

u/Repulsive-Song-1594 9h ago

i understand the start stop step the thing is i dont know how to use functions inside of it despite me knowing they play by the row its hard t o understand even a simple multiplication is hard for me to do

1

u/Slothemo 20h ago

If you want a hint, look into something called the Sliding Window algorithm.

1

u/Naive_Programmer_232 18h ago edited 17h ago

EDIT: Ignore this comment, see other reply for cumulative sum functions. this is not an example of that.


are you saying like this?

ex:

   def next_sums(arr: list[int]) -> list[int]:
       """
       ex: [1,2,3,4]
       e.g 1+2,2+3,3+4 ... {curr}+{next}
       """
       res=[]
       for i in range(len(arr)-1):
           res.append(arr[i]+arr[i+1])
       return res

   def prev_sums(arr: list[int]) -> list[int]:
       """
       ex: [1,2,3,4]
       e.g. 1+2,2+3,3+4 ... {prev}+{curr}
       """
       res=[]
       for j in range(1,len(arr)):
           res.append(arr[j-1]+arr[j])
       return res

Even though these are written different, they produce the same result. You can easier see these are the same by considering:

    next_sums addition:   arr[i]+arr[i+1]

                     let  j=i+1
                          j-1=i+1-1=i

                     thus,

    prev_sums addition:   arr[j-1]+arr[j]

here is a test to make sure they produce the same result:

   def run_all_tests() -> None:
       
       test_map = {
           "odd": [2,4,6,9,12],
           "even": [2,4,6,9,12,15],
           "empty": [],
           "single": [5],
           "duo": [5,10],
       }

       for test_name,arr in test_map.items():
           if next_sums(arr)==prev_sums(arr):
               print(f"passed {test_name} ✓")
           else:
               print(f"failed {test_name} X")
       

   run_all_tests()
   passed odd ✓
   passed even ✓
   passed empty ✓
   passed single ✓
   passed duo ✓

1

u/Repulsive-Song-1594 9h ago

it isnt that i dont understand what range function do the problem is that i find it hard to use lists and numbers and function in it

5

u/BranchLatter4294 22h ago

Practice with it for a few minutes. There are only 3 parameters (start, stop, step). Experiment and observe the behavior.

2

u/tb5841 22h ago

range(n) produces an object.

If you put in 5, for example, range(5) produces the numbers 0, 1, 2, 3, 4.

It starts at 0 by default, goes up by 1 each time by default, and goes up to just before the number you put in.

You can change where it starts, and what it goes up by each time, but don't worry about that for now.

There are two things that make it seem confusing. One is that you most often see it in 'for' loops, and if you're not happy with loops yet then that won't make sense. The other is that the return value of the range() function, that contains the numbers 0, 1, 2, 3, 4, is a type of object you haven't come across yet.

Don't find a video. Open Python, type stuff, and see if you can work out what's happening. Avoid anything with a 'for' loop for now. Some stuff worth trying out:

r = range(5)

print(r)

print(list(r))

print(3 in r)

print(5 in r)

print(set(r))

...etc.

2

u/mountain-snowman 21h ago

Just read this 2 mins documentation from the devs: https://docs.python.org/2/library/functions.html#range

1

u/Sea-Ad7805 22h ago

It's easy, look at this example by clicking Memory Graph Web Debugger and see its state change step by step.

1

u/Adrewmc 22h ago

What’s the problem.

https://docs.python.org/3/builtins/stdtypes.html#range

The docs are fairly explicit on the range object.

1

u/johlae 12h ago

Look at that, with examples even. Pity it's videos they want.

I do not get the problem either.

1

u/AndrewBorg1126 21h ago edited 21h ago

I don't mind it being an hour long

Meanwhile, here I am wondering how there would possibly even be enough stuff involved in it to spend an hour talking about range.

It gives you a range of numbers described by the parameters. It's worth examining the edge behaviors like whether bounds are inclusive or exclusive, maybe what happens when the step size excludes the second bound as an element, but aside from that what really is there to talk about?

1

u/atarivcs 21h ago

The purpose of the range function is to create a sequence of integers. Usually you would then use this sequence in a for loop, but there are other uses too.

range() can take one, two, or three arguments.

If you pass one argument, the sequence starts at 0 and continues up to (but not including) the argument. So for example range(5) produces the sequence 0,1,2,3,4.

If you pass two arguments, the sequence starts at the first argument and continues up to (but not including) the second argument. So range(4,11) produces the sequence 4,5,6,7,8,9,10.

If you don't want the sequence to be consecutive, you can pass a third argument which is used as the "step" increment between values. range(1, 8, 2) produces the sequence 1,3,5,7.

What is the exact problem you have having?

1

u/aiuniverse-3p3_here 18h ago

Bro, range is simple, don't crash out!

range(5) = 0,1,2,3,4 It starts from 0 and stops before 5.

range(1,6) = 1,2,3,4,5 First number is start, second is stop.

range(0,10,2) = 0,2,4,6,8 Third number is step, how much to jump.

Try this: for i in range(5):     print(i)

You'll see 0 to 4. That's it!

1

u/Due-Mortgage-6854 22h ago edited 7h ago

It's easy don't worry range(start, stop, step)

Now as example, let's say

  • You book time off work starting the 10th and tell your boss, "I'll be back at my desk on the 15th." You are off on the 10th, 11th, 12th, 13th, and 14th. Because you return on the 15th, that day isn't part of your vacation. That is why Python stops right before the second number So your start here is 10 and stop is 15!

  • You decide to hit the gym every other day for the month of June (which has 30 days), starting on June 1st. You start on the 1st, skip a day (step = 2), go on the 3rd, 5th, 7th, all the way up to the 29th. You set the stop number to 31 so that the 30th isn't accidentally cut off before the month ends. Here start is 1, stop 31 and step 2!

  • If you want some more help : https://discord.com/invite/QWGWKFVYyh