[Python] Short Python code not showing what I expected

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    Hello there fellow developers,

    The following is a question from a Python's studying list. The question asks to choose between 5 answers about which would be the output of print(v, m, n).

    a) [1, 2, 3], [2, 4, 6], [3, 6, 9]

    b) [3, 6, 9], [3, 6, 9], [3, 6, 9]

    c) [1, 2, 3], [1, 2, 3], [3, 6, 9]

    d) [1, 2, 3], [1, 2, 3], [2, 4, 6]

    e) [3, 6, 9], [1, 2, 3], [3, 6, 9]

    From my beginner perspective, v = [1, 2, 3] and m after running f1(v) should be m = [1, 2, 3] as well (and on debug I see m as [1, 2, 3] before hitting the n = f2(v) line). Then n should be [3, 6, 9] after running f2(v)(because of m *= 3). I know the right answer is B, I just cannot figure out why. Although wrong, my thinking process point to [1, 2, 3][1, 2, 3][3, 6, 9] as the answer.

    def f1(v):
    for elem in v:
    elem *= 2
    return v

    def f2(m):
    for i in range(len(m)):
    m *= 3
    return m

    v = [1,2,3]
    m = f1(v)
    n = f2(v)

    print(v, m, n)


    Please help me figure out why the output of this Python code is

    [3, 6, 9]
    [3, 6, 9]
    [3, 6, 9]


    instead of

    [1, 2, 3]
    [1, 2, 3]
    [3, 6, 9]


    Thanks.

    Continue reading...

Compartilhe esta Página