Use variable name, not its value [duplicate] - python

This question already has answers here:
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 2 years ago.
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.

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.

Related

Indexing a list a variable amount of times, based on specified key [duplicate]

This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 2 years ago.
Let's say hypothetically you had a variable called list_a. Sometimes the objects inside are themselves also lists, so multiple indexing might be needed depending on what you want.
You have the following dictionary:
field_dict = {
'name':[1],
'birthdate':[2,5],
'gender':[5,1,3]
}
Each value in the lists above represent how to index list_a to access the needed value.
To get a person's name, I just need to index list_a once, like this: list_a[1].
To access their birthdate, I do list_a[2][5]. This is where the multiple indexing comes in. Likewise, to access gender, I do list_a[5][1][3].
I wonder what the most elegant implementation of this would be - the only solutions I can think of would involve a bit of bruteforcing in the way of hard-coding some details excessively.
As noted in the comments, this does not seem like a great data model. But leaving that aside, I might implement the accessor like:
def get_item(obj, indices):
if indices:
return get_item(obj[indices[0]], indices[1:])
else:
return obj
or iteratively:
def get_item(obj, indices):
while indices:
obj = indices[0]
indices = indices[1:]
return obj

How to pass a specific value from Tuple into a function [duplicate]

This question already has answers here:
Getting one value from a tuple
(3 answers)
Closed 2 years ago.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(a_tuple(variable1))
Is there a way I can pass a specific value from a tuple into a function? This is a terrible example, but all I need to know is if I can pass variable1 from the tuple into the function, I understand in this instance I could just pass in variable 1, but its for more complicated functions that will get its data from a tuple, and I don't like the look of that many variables, too messy.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(*a_tuple)
This code would obviously provide an error as it unpacks the tuple and inserts 2 variables, to make this work in my program I would need a way to pass either variable1 or variable2 into the function. My question is can I define exactly which items from a tuple are passed into the function when calling the function? Latest version of Python if it matters.
P.S. I wrote print("hello world") for the first time 7 days ago, this is my first language and my first question I couldn't find an answer to. Go easy on me, and thank you for your time.
In the code you provided you don't have a tuple you have a list. But it is still pretty much the same.
In your example lets say that you wanted to pass the first variable you would do it like this:
my_function(a_tuple[0])
If you don't understand why there is a zero here and how does this work I highly suggest learning about lists before functions.
You just need to access individual elements of the tuple, using index notation:
my_function(a_tuple[0])
or
my_function(a_tuple[1])
You could, if you wanted, write a new function which takes a tuple and an index, and calls my_function with the appropriate element:
def my_other_function(tuple, index):
return my_function(tuple[index])
But I don't see how there would be much gain in doing that.
you can index a tuple or use the index method.
def my_function(a):
pass
my_function(a_tuple[0])
if you want to get the index of a value use the index() method
a_tuple.index(variable1) #this will return 0

Why does this function modify a variable outside of it? [duplicate]

This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 3 years ago.
I've got this function that removes the second data value from a list (simplified). However when executing the function, the original list seems to get modified even though I'm only doing something to the variable inside the function.
print(data_values)
def remove_2(data):
data.pop(2)
return data
new_data = remove_2(data_values)
print(data_values)
>>>['a', 'b', 'c', 'd']
>>> ['a', 'b', 'd']
I'm printing out the original data_values both times, but the second time it's the modified version even though only the variable inside the function was modified.
The pop() function removes the element with the given index what you're doing is removing the element with index 2 from the original list and then using another list to display it
print(data_values)
def remove_2(data):
data.pop(2)
return data
new_data=data_values[:]
new_data = remove_2(new_data)
print(data_values)
print(new_data)
You should use another list if you don't want the default list to be changed

Python _ meaning when assigned after for loop [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 5 years ago.
I am not an experienced Python programmer and I saw following code which I couldn't understand. Unfortunately syntax is very tricky and difficult to search for on the internet. Though I did find some explanation to '_' and '__' but I am not sure if following code has any special meaning for '_'
if not allowed_positions:
return (0, 0)
_, point = max([(self.point(graph.find_point(p), self), p) for p in allowed_positions])
In the above code I don't understand why there is an underscore with comma '-,' before point = ....
_ is just used as a placeholder for a discarded variable.
Let's assume there is a function which returns a tuple with two elements, and I am interested only in the second part of the tuple, then it is a general practice to use _ for the variable I do not need.
e.g.
>>> def return_tuple():
... return (24,7)
...
>>> _, days = return_tuple()
>>> days
7
_ is a placeholder for variables that you don't need to store data in.
You can use it for tuple unpacking and it's common to practice to use an underscore to denote that that value will not be used later in the script.
If you had something like this: soldiers = [('Steve', 'Miller'), ('Stacy', 'Markov'), ('Sonya', 'Matthews'), ('Sally', 'Mako')]
and, you wanted to get only the last names you would do this:
for _, last_name in soldiers:
# print the second element
print(last_name)
Instead of doing:
for first_name, last_name in soldiers:
print(last_name
Since you don't need to use first_name. You replace it with _ so you don't store unnecessary variables

How to get a copy from a list? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 9 years ago.
I am trying to get an element from list and make some change on this element (which is also a list). Weirdly, the change applied on the previous list. Here is my code:
>>>sentences[0]
['<s>/<s>',
'I/PRP',
'need/VBP',
'to/TO',
'have/VB',
'dinner/NN',
'served/VBN',
'</s>/</s>']
>>>sentence = sentences[0]
>>>sentence.insert(0,startc); sentence.append(endc)
>>>sentences[0]
['<s>/<s>',
'<s>/<s>',
'I/PRP',
'need/VBP',
'to/TO',
'have/VB',
'dinner/NN',
'served/VBN',
'</s>/</s>'
'</s>/</s>']
It is like I just got a pointer to that element, not a copy
You do get a "pointer", in fact. Lists (and any mutable value type!) are passed around as reference in Python.
You can make a copy of a list by passing it to the list() object constructor, or by making a full slice using [:].
a = [1,2,3]
b = a
c = list(a)
d = a[:]
a[1] = 4 # changes the list referenced by both 'a' and 'b', but not 'c' or 'd'
You're exactly right! In Python, when you pass a list as an argument to a function, or you assign a list to another variable, you're actually passing a pointer to it.
This is for efficiency reasons; if you made a separate copy of a 1000-item list every time you did one of the aforementioned things, the program would consume way too much memory and time.
To overcome this in Python, you can duplicate a one-dimensional list using = originalList[:] or = list(originalList):
sentence = sentences[0][:] # or sentence = list(sentences[0])
sentence.insert(0,startc)
sentence.append(endc)
print(sentence) # modified
print(sentences[0]) # not modified
Consider using list comprehension if you need to duplicate a 2D list.

Categories