-3
def test(lister):
    lister.append('why am i being shown in output?')

def pass_the_list():
    x = []
    test(x)
    print(x)

pass_the_list()

Output

['why am i being shown in output?']

Process finished with exit code 0

how to pass string as a reference without return?

GokusSG
  • 9
  • 2

2 Answers2

2

The list x is passed as a reference not value, therefore changes made in the function will preserve also when the function finishes.

L. Letovanec
  • 535
  • 2
  • 6
1

You can pass a string as a refence, but it doesnt matter, because string, unlike list, is immutable. So any change you do to the string will cause creation of a new object.

test_string = 'Test my immutability'
test_string[0]='B'
>> TypeError: 'str' object does not support item assignment

You can modify string like this though (by putting it into something mutable like list)

test_string = 'Test my immutability'

test_list = [test_string]


def reference_test(test_list):
    test_list[0]=test_list[0].replace('Test','Fest')

reference_test(test_list)

print(test_list)
>> ['Rest my immutability']
Martin
  • 3,333
  • 2
  • 18
  • 39