-3

I want to use a variable to call a global list with the same name. So, for example:

x = [1,2,3,4]
y = [2,3,4,5]

def function(i):
    return i

function(x)
    expected output -> [1,2,3,4]
V__M
  • 21
  • 4
  • 3
    pass x or y to the function? – Padraic Cunningham Apr 26 '15 at 21:43
  • possible duplicate of [How can I use a string with the same name of an object in Python to access the object itself?](http://stackoverflow.com/questions/9396706/how-can-i-use-a-string-with-the-same-name-of-an-object-in-python-to-access-the-o) – ivan_pozdeev Apr 27 '15 at 04:45

1 Answers1

3

I assume you mean that

>>> x = [1,2,3,4]
>>> x == function('x')
True

where passing the string 'x' to the function returns the list assigned to x.

You don't want to write code that depends on the names of variables; instead, keep a dictionary that maps strings to your lists.

>>> d = dict(x=[1, 2, 3, 4], y=[2, 3, 4, 5])
>>> d['x']
[1, 2, 3, 4]
chepner
  • 497,756
  • 71
  • 530
  • 681