triplepla1
triplepla1

Reputation: 25

Range length in python

I'm trying to make a program that spells an entered word in reverse. I finally got it to work, but I don't understand why it works. Here is the working program:

    def reverse(text):
    length = len(text)
    text = list(text)
    new = ["None"] * length
    for i in range(0, length):
        new[i] = text[length - i - 1]
    return "".join(new)
return new

Shouldn't making i range(0, length) be one character longer than the original word? Ex. if the original word is four characters, range(0, length) would be five characters, wouldn't it? Seems like the range should be (0, length - 1), but that didn't work! Could someone please explain why?

Upvotes: 0

Views: 15337

Answers (3)

holdenweb
holdenweb

Reputation: 37013

I presume you are learning Python (so am I, and have been for over 20 years now - there's always more to learn!) so first of all congratulate yourself on having produced code that works!

If you have used string slicing then you may know that x[:] creates a new copy of the sequence x (string, lists and tuples are all considered to be sequences), containing exactly the same elements. You may even also know that you can use a "stride" as the third element of a slice.

What you may not know is that using a stride of -1 will iterate backwards through the elements. So a shorter version of your reverse function might read

def reverse(x):
    return x[::-1]

It isn't unusual for newer Python users to discover that efficient ways of doing things they have been doing inefficiently are built into the language, so consider this not a criticism of your code but a suggestion for possible improvement.

Upvotes: 0

Shoeboom
Shoeboom

Reputation: 88

Once it reaches length the loop ends. For example

str1 = "hello"
length = len(str1) #length = 5  
for i in range(0,length) # will loop from 0 to 4.
    print(length)

Output:

0
1
2
3
4

in the example, the loop will run for 1 less than length

Upvotes: 1

Artyer
Artyer

Reputation: 40801

Python ranges go until it is reached, stopping when it does.

Writing a range out as a for loop looks like this:

for i in range(a, b, c):

for (int i = a; i < b; i += c) {

So it doesn't include the end point.

Note that the < means that it doesn't include b. You might be thinking of it as <=.

And, in this case, you can just use the built-in reversed, or slice by [::-1] (From the end, to the start, going back by a character each time.)

Also note that range(0, x) is equivalent to range(x),

Upvotes: 2

Related Questions