Python Forum
Understand for range concept
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understand for range concept
#1
Hi everyoine,

I had a doubt about for range in Python when I also use string length or array, for example:
def name(s): 

    l = s.split() 
  
    for i in range(len(l)-1): 
        s = l[i] 
        print(s)
                     
s ="mohandas karamchand gandhi" 
print(name(s)) 
output : 
mohandas
karamchand
None
def name(s): 

    l = s.split() 
  
    for i in range(len(l)+1): 
        s = l[i] 
        print(s)
                     
s ="mohandas karamchand gandhi" 
print(name(s)) 
output : 
mohandas
karamchand
gandhi
Why if I change the operator in Len (s) [ + / - ] 1, does it give me different results?
Regards,
RavCoder
Reply
#2
Don't use this style. In Python it is done like:

>>> s ="mohandas karamchand gandhi" 
>>> for word in s.split():
...     print(word)
... 
mohandas
karamchand
gandhi
As for range you can simply observe by printing out:

>>> s = 'abc'
>>> len(s)
3
>>> first = len(s) + 1
>>> first
4
>>> second = len(s) - 1
>>> second
2
>>> list(range(first))
[0, 1, 2, 3]
>>> list(range(second))
[0, 1]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
  
    for i in range(len(l)-1): 
        s = l[i] 
        print(s)
                     
s ="mohandas karamchand gandhi" 
You are making a list of the elements after splitting the string "mohandas karamchand gandhi". So the positions and values of that list are:
l[0] = 'mohandas'
l[1] = 'karamchand'
l[2] = 'gandhi'

Therefore, the len(l) = 3 because the list has 3 elements: ['mohandas', 'karamchand', 'gandhi']. Consequently, len(l)-1 = 3 -1 = 2 and as a result, range(len(l)-1) = range(2). The function range starts at '0' (if you don't write anything else) and ends with a number a unit less than the limit (the limit number is not used). So range(2) means numbers 0 and 1.

So you then make the program print the elements of that list and positions:
l[0] = 'mohandas'
l[1] = 'karamchand'
and my understanding is that because you asked to print the whole string with print(s), but had previously limited the list to be printed with positions '0' and '1', the last element of the list is printed as 'None'.

    for i in range(len(l)+1): 
        s = l[i] 
        print(s)
                    
s ="mohandas karamchand gandhi" 

In a similar way, len(l)+1 = 3 + 1 = 4 and as a result, range(len(l)+1) = range(4). The function range starts at '0' (if you don't write anything else) and ends with a number a unit less than the limit (the limit number is not used). So range(4) means numbers 0, 1, 2 and 3.

So you then make the program print the elements of that list and positions:
l[0] = 'mohandas'
l[1] = 'karamchand'
l[2] = 'gandhi'
l[3] produces an IndexError: list index out of range as there are no elements in the list in position [3].

I hope it helps.

All the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#4
Whenever you see range(len(...)) there is probably a better way to do it.
See Ned Batchelder's talk - Loop like a native
Reply
#5
I agree with Perfringo and Jefsummers that there are better ways to do what you wanted with your code.

Nevertheless, I tried to explain the concept of the function range() and how it works, so I didn't pay much attention to the rest of the code. Later on, I wondered myself why that 'None' appeared, and then I noticed that you put at the end of your code the line:

print(name(s))
so you are asking to print a function (name(s), defined by yourself, that has already a print() function in it:

print(s)
so there is no need to write that last line of your program as print(name(s)). You just need to call the function for that string with:

name(s)
With that modification, your program:

def name(s): 
 
    l = s.split() 
   
    for i in range(len(l)-1): 
        s = l[i] 
        print(s)
                      
s ="mohandas karamchand gandhi" 
name(s)
produces the following output:
Output:
mohandas karamchand
and your other version of your program with my modification:
def name(s): 
 
    l = s.split() 
   
    for i in range(len(l)+1): 
        s = l[i] 
        print(s)
                      
s ="mohandas karamchand gandhi" 
name(s)
produces the following output, with an error message:
Output:
mohandas karamchand gandhi
Error:
Traceback (most recent call last): File "C:/Users/User1/AppData/Local/Programs/Python/Python37/aaa1.py", line 10, in <module> name(s) File "C:/Users/User1/AppData/Local/Programs/Python/Python37/aaa1.py", line 6, in name s = l[i] IndexError: list index out of range
The program following your code to produce the desired output (but keep in mind that there are better ways to do it) is:

def name(s): 
 
    l = s.split() 
   
    for i in range(len(l)): 
        s = l[i] 
        print(s)
                      
s ="mohandas karamchand gandhi" 
name(s)
and produces the following output:
Output:
mohandas karamchand gandhi
All the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x axis range goes over the set range Pedroski55 5 3,217 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  How we prune Alphabeta Tree Node Using BST concept Anldra12 4 2,428 May-18-2021, 09:17 AM
Last Post: Anldra12
  Define a range, return all numbers of range that are NOT in csv data KiNeMs 18 7,074 Jan-24-2020, 06:19 AM
Last Post: KiNeMs
  Understanding the concept ( Modules , imports ) erfanakbari1 1 2,196 Nov-25-2019, 01:59 AM
Last Post: Larz60+
  help with multiprocess concept kiyoshi7 2 2,485 Aug-10-2019, 08:19 PM
Last Post: kiyoshi7
  Recursion concept Truman 8 8,695 Oct-06-2018, 07:48 AM
Last Post: Larz60+
  Concept of batch files Truman 2 2,838 Jul-23-2018, 09:02 PM
Last Post: Truman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020