⊗pyPmFnPR 6 of 128 menu

Passing Variables by Reference in Python

In Python, variables containing complex objects are passed by reference. This means that all changes made to one variable will be reflected in the second. Although this type of value assignment increases the risk of an error, it significantly saves system memory resources of the OS.

Let us have two lists:

lst1 = [1, 2, 3, 4, 5] lst2 = lst1

Since the variable lst2 has been assigned the value lst1, the computer's RAM now stores a single list that is referenced by two variables at the same time.

Let's change the first element of lst2 and print the first list to the console:

lst2[0] = '!' print(lst1) # ['!', 2, 3, 4, 5]

What will be the result of running the following code:

lst1 = [1, 2, 3, 4, 5] lst2 = lst1 lst2[0] = '!' print(lst1)

What will be the result of running the following code:

lst1 = [1, 2, 3, 4, 5] lst2 = lst1 lst2[0] = '!' print(lst2)

What will be the result of running the following code:

lst1 = ['a', 'b', 'c', 'd'] lst2 = lst1 lst3 = 'e' lst2[2] = lst3 print(lst2)
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline