'Why do new variable names need to be on the left of the equals (=)?
I am curious as to why a certain format produces an error while the other doesn't.
Code that works:
name = input().split()
if len(name) == 3:
first_name, middle_name, last_name = name
print(f'{last_name}, {first_name[0]}.{middle_name[0]}.')
elif len(name) == 2:
first_name, last_name = name
print(f'{last_name}, {first_name[0]}.')
Code that does not work:
name = input().split()
if len(name) == 3:
name= first_name, middle_name, last_name
print(f'{last_name}, {first_name[0]}.{middle_name[0]}.')
elif len(name) == 2:
name = first_name, last_name
print(f'{last_name}, {first_name[0]}.')
The only difference in these two are in lines 4 and 8 where the name = ends up being. I always put the variable on the left so i'm lost as to why this needs to be on the right.
Thanks!
Solution 1:[1]
Those say two entirely different things. The second one takes three objects (first_name, middle_name, last_name), then builds them into a tuple, and assigns that to name. That's clearly not what you want, since those three names do not exist. Your first example takes the three parts of the variable name (which does exist), and unpacks them into those three objects. Your second sample is just not the way you write an assignment statement. An assignment takes what's on the RIGHT, and assigns it into what's on the LEFT.
After all, you write:
num = 3
and not
3 = num
right?
Solution 2:[2]
If you're new to programming or you're more familiar with math notation, the concept of = might be confusing, because it's not actually an equivalence, it's more like naming. When you write a statement of the form name = value, like for example foo = 0, that means, "take the value 0 and store it under the name foo". You can think of name as a label if that helps your understanding.
In your case, you want to take the strings from the list name and store them under the labels first_name, possibly middle_name, and last_name, respectively. To demonstrate, let's say name is ['John', 'Doe']. That means you want to store 'John' under first_name and 'Doe' under last_name. So how you do that is to write,
first_name, last_name = name
If we substitute name with the value that it references, it becomes clearer:
first_name, last_name = ['John', 'Doe']
Then Python unpacks the list and this becomes equivalent to:
first_name = 'John'
last_name = 'Doe'
For reference, the exact semantics are explained in The Python Language Reference: Assignment statements. (Syntactically, target_list has multiple targets, all of which are identifiers, and the RHS is a starred_expression which boils down to primary -> atom -> identifier.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 |
