[Tutor] Problem with code interating thri a list

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 2 19:30:47 EDT 2016


On 02/08/16 15:59, Chris Clifton via Tutor wrote:

> My Logic:  Since a string is immutable, I converted it to a list

That is certainly one approach but your solution has some snags.
In fact its probably not necessary unless you want to play with
big strings. You could just build a new string from the old one. But as
strings get bigger building them incrementally
gets more expensive.

> the print statements in the code are for my debugging and will be removed in the end. 

That's good :-)
I'll remove them for clarity.

> def convert(text):
>     text = list(text)
>     for item in text:
>         if item == item.lower():
>             item = item.upper()
>         else:
>             item = item.lower()
>         result = "".join(text)
>     return result

First thing is that changing item does not change the
item in the list. You need to use enumerate() to get
the index and use that to reassign the list entry.

like:

for index,item in enumerate(text):
    .....
    text[index] = item.lower()

Secondly you probably want to do the join() outside
the loop.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list