[Python] Why does Python treat two identical string literals differently when modified inside...

Discussão em 'Python' iniciado por Stack, Novembro 30, 2025.

  1. Stack

    Stack Membro Participativo

    was experimenting with string handling and noticed something confusing.

    In the following code, two identical string literals behave differently depending on where they are used:

    s1 = "harsh"
    s2 = "harsh"

    print(s1 is s2) # True (expected: Python interns identical literals)


    But when I try something similar inside a loop with string concatenation:

    values = []

    for i in range(3):
    x = "harsh" + ""
    values.append(x)

    print(all(v is values[0] for v in values))


    This prints:

    False

    Continue reading...

Compartilhe esta Página