pythonloopsfor-looprange

Using range function in Python


I am new to learning Python and have a question about using the range function to iterate a string.

Let's say I need to capitalize everything in the following string:

string = 'a b c d e f g'

Can I just write the following code?

for i in string:
    i = i.upper()
return string

Or should I use the range function to iterate every element in the string?

Finally, a more general question is whenever I need to iterate all elements in a string/list, when should I use the range function and when can I just use the "for" loop?


Solution

  • Strings are a bad example, because strings in Python cannot be changed. You have to build a new one:

    new = ''
    for i in string:
        new += i.upper()
    

    For the sake of example, we're all going to ignore the fact that new = string.upper() would do this in one statement.

    In general, when you iterate through an object, you are handed references to the members. You can't change the container object, but if the inner object is mutable, you can change it. Consider this silly example:

    a = [[1],[2],[3],[4]]
    for element in a:
        element[0] *= 2
    

    This will result in a being [[2],[4],[6],[8]], because we are allowed to modify those inner lists. We can't change the outer list.

    AS A GENERAL RULE, if you find yourself writing for i in range(len(xxx)):, then there is a better way to do it. It isn't ALWAYS true, but it's a key Python learning point.