Skip to content Skip to sidebar Skip to footer

List As A Function Argument - Modifications Discarded

I have a following code def hidePasswords(L, password): for elem in L: if elem == password: elem = '*'*len(password) return L print(hidePasswords(['tes

Solution 1:

khelwood has given a good answer (as usual), but I'll just add a few more points.

Thinking about how Python works in terms of concepts from other languages like pass-by-value and pass-by-reference isn't so helpful. Rather than thinking about variables, their contents and pointers to them, try to adopt the Pythonic viewpoint and think in terms of objects being bound to names, and whether or not the objects (and their contents) are mutable or not.

These concepts are not only important in understanding what happens when you call a function in Python, it applies generally, even to simple assignments. In other words, although an assignment statement may look like an assignment statement in other languages, what's really happening is not quite the same.

Stack Overflow regular Ned Batchelder has a great article with cute diagrams on this topic: Facts and myths about Python names and values

Here's a variation on your code that mutates the list passed to it. The usual Python convention is that functions that mutate an object do not return it (although sometimes it's convenient to bend that convention).

#! /usr/bin/env python

def hidePasswords(L, password):
    for i, elem in enumerate(L):
        if elem == password:
            L[i] = "*" * len(password)
    return

words = ["test", "test1", "test8"]
hidePasswords(words, "test")
print(words)

output

['****', 'test1', 'test8']

Solution 2:

In this code:

def hidePasswords(L, password):
    for elem in L:
        if elem == password:
            elem = "*"*len(password)
    return L

In the loop, elem is being set to each value in L. Then you reassign elem to be something different. So it was the value in L, then it is something else. That doesn't affect the value in L, because elem isn't a reference.

You could write this more succinctly as:

def hidePasswords(L, password):
    return ['*'*len(password) if elem==password else elem for elem in L]

Post a Comment for "List As A Function Argument - Modifications Discarded"