Home > Net >  Python - do tuples copy the contents of lists or is it a reference?
Python - do tuples copy the contents of lists or is it a reference?

Time:12-24

I want to return a list and a status code from a method in Python. I'm thinking of using a tuple because of its simplicity, but the issue is that the list may be huge, thus, copying it again into a tuple would result in some performance issues. Which is why I ask - does Python copy a list inside a tuple, or does Python take it as a reference?

Here's an example of what I'm trying to do:

response = requests.get(self.base_url)
my_list = ast.literal_eval(response.text) # this just turns the string literal into a list
return (response, my_list)

CodePudding user response:

You'll be fine.

my_list = ast.literal_eval(response.text) 
x = (response, my_list)

will not copy the list, it will just be referenced in the tuple's second element.

You could try what happens to my_list if you do x[1].append("foo")...

CodePudding user response:

Python takes it as a reference. You can verify this by creating a list, a tuple that contains the list, and then modifying the list and seeing whether the contents of the tuple change as well:

lst = [1, 2, 3]
tup = (lst, 2)
lst[1] = 5
print(tup)

This outputs:

([1, 5, 3], 2)

If tup made a copy of the list, the tuple's first element would be [1, 2, 3].

  • Related