-1

What?

I want to use a variable's name, not it's value. For instance, in the following example, I would like the function to return my_list[1] , and not B..

my_list = ['A', 'B']
def example(list_element):
   print(repr(eval(list_element)))

example(my_list[1]) # I would like this to print `my_list[1]`

But Why?

I am trying to create a function that takes a given element from a list, and also uses the previous list element. By getting the name my_list[1], I can subtract one and also get my_list[0]. Once I have both the names, I can utilise the values stored under these names.

Yes, I could simply add two fields to the function and put them in each time but I was hoping to keep the body of my code a little easier to read.

10
  • do you mean print(f"{list_element=}")? Commented Dec 16, 2020 at 20:30
  • 5
    Objects don't know which variables they happen to be bound to at any given time. Are you planning on hardcoding this to only work with one specific variable "my_list" or should be be generic? Commented Dec 16, 2020 at 20:30
  • 1
    @grismar What do you propose instead? leaving the same questions open? I put the "Dont do it" and advice of "return a slice from the list or maybe a tuple of prev/act value" in the comment. if we leave it open, the same bad crappy answers turn up - using eval, using inspect, search through global() etc Commented Dec 16, 2020 at 20:38
  • 2
    @PatrickArtner - no, providing a simple answer that goes into the difference between data and code. Mine below is about as simple an answer as OP needed. You could write a nicer answer that concisely explains the difference and results in a similar solution. What the referenced answers do is "sure, if you want to be an idiot: here's how" - they're not wrong, but they're no good to the beginning coders that just don't know any better and the answer will just send them further down a dead end. Commented Dec 16, 2020 at 20:41
  • 1
    @SolebaySharp - that's good to hear, and means you're on your way to better things. My comment was more general, questions like these come up more than daily. But thanks for the feedback. I think we can leave this as it is :) Commented Dec 16, 2020 at 20:44

1 Answer 1

2

Don't use data to manipulate your code, it's not how Python (or most languages) works.

To do what you're trying to do:

my_list = ['A', 'B']


def example(a_list, index):
    print('The element passed: ', a_list[index])
    print('The element before it: ', a_list[index-1])


example(my_list, 1)

Of course this doesn't check if you didn't accidentally pass 0, etc. - but it shows you don't need to make a mess with eval, exec, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is a sensible solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.