Pigna
Pigna

Reputation: 2924

Why the "while" loop works but the "for" one doesn't?

I've just started learning python. I'm trying to make a reverse function for strings, and I know this code works:

def reverse(text):
    string_list = list(text)
    new_list = []
    length = len(string_list) - 1
    while length >= 0:
        new_list.append(string_list[length])
        length = length - 1
    return ''.join(new_list)

but I don't understand why this one doesn't:

def reverse(text):
    string_list = list(text)
    new_list = []
    for i in len(text)-1:
        new_list.append(string_list[len(text)-i])
    return "".join(new_list)

How to make the for loop work? Where's the error?

Upvotes: 0

Views: 97

Answers (4)

Ayush Gupta
Ayush Gupta

Reputation: 59

Start from index 1 and use range()

for i in range(1,len(text)+1):

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20359

Got the error, use this in corresponding line

for i in range(len(text))

and

new_list.append(string_list[(len(text)-1)-i])

Upvotes: 0

HavelTheGreat
HavelTheGreat

Reputation: 3386

Try something like this:

def reverse(text):
    string_list = list(text)
    new_list = []
    for i in range(len(text)):
        new_list.append(string_list[len(text) -1- i])
    return "".join(new_list)

reverse('joe') => 'eoj'

With this code you will neither have a list index out of range error nor miss a character from your string.

Upvotes: 1

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52183

You should use range or better xrange:

for i in xrange(len(text)):
    new_list.append(string_list[len(text) - 1 - i])

Upvotes: 2

Related Questions