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
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 10 months ago.
Say I have a python list with 5 elements; list = ['a','b','c','d','e']. And I want to change it into 5 different strings so that each element is its own string, for example,
str1 = a str2 = b str3 = c str4 = d str5 = e
How would that be done?
Note: I would want it to be done autonomously if possible as the number of elements in a list is variable according to the data that is input at the beginning of the original code.
list_ = ['a','b','c','d','e']
You can use something called list unpacking, that you can do this way:
a, b, c, d, e = list_
As #Mark told you in the comments...
I'd be curious to know when str1, str2, etc. is preferable to s[1] , s[2]. It sounds like you are about to make a mistake you will later regret.
...you should avoid this approach.
If you don't know the lenght, you should read this, which suggests you to use the * star operator...
first, second, *others, third, fourth = names
...until you have the whole list unpacked.
Since you don't want to write an hell of if/elif/else over the lenght, I would suggest you to use exec to create variables on fly, even if (like Mark said) it's a bad idea.
I really want you to get that this is a bad idea, but you can use unpacking for useful scopes, in this case I would suggest you to read this, this and the respective PEP.
This question already has answers here:
python: why does replace not work?
(2 answers)
Closed 1 year ago.
a = 'dog'
a.replace('dog', 'cat')
print (a)
Really basic question, the function seems to be fairly straightforward but it just isn't replacing in this instance for some reason - is it because replace doesn't inherently change "a"?
Yes, you are correct. It won’t modify a.
Replace function will return a replaced string.
So, if you like to replace the text in a. Use the below code.
a = 'dog'
a = a.replace('dog', 'cat')
print (a)
Strings are immutable data types in Python which means that its value cannot be updated. Variables can point at whatever they want.
str.replace() creates a copy of string with replacements applied. See documentation.
Need to assign a new variable for the replacement.
a = 'dog'
b = a.replace('dog', 'cat')
print(b)
Output:
cat
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.
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 3 years ago.
I saw a function like bellow, I don't know the _ meaning.
def child_handler(signum, _):
logging.warn('received SIGQUIT, doing graceful shutting down..')
what's the _ there?
but, however, if we ignore the _, why we need there an ignored param?
the _ variable is just a way to say that it's not going to be used further down the line.
Basically, you don't care what the name is because it'll never be referenced.
It essentially is a way of ignoring the value of the variable, and we don't want to use it down the line.
Another way of thinking is that it is a placeholder for the value that will be ignored
def func(a, b):
return a,b
#I care about both return values
c,d = func(2,3)
#I don't care about the second returned value, so I put a _ to ignore it
c, _ = func(2, 3)
Another good use case of this is when you are running a for loop, but don't care about the index.
for _ in range(10):
#do stuff
Even for functions, it acts like a don't care variable
def func(a, _):
print(a)
func(1, 5)
The output will be 1
The underscore _ in Python can be used for different cases. In this case it means that the second argument of the child_handler function is ignored (so-called "Don't care").
This question already has answers here:
How can you set class attributes from variable arguments (kwargs) in python
(13 answers)
Closed 8 years ago.
This is what I would like.
def add_things_to_x(x,list_of_things):
for item in list_of_things:
x.item = item
return x
How can I do this?
And as it seems so hard to do I am guessing there may be a better way and a reason not to do this?
An example of how I might use such a function.
average_height = 10
std_height = 3
x = load_data()
x = add_things_to_x(x,[average_height,std_height])
x.save_data()
so that later on if I pickle.load(x) I could do call x.std_height and x.average_height
Use setattr for that sort of thing:
for k, v in {'average_height': 10, 'std_height': 3}:
setattr(x, k, v)
At the moment at the end you've set x.item to different values ending up with just the last one. This evades that problem because the name of the attribute is sent as a string parameter.