What is the generally preferred way of assigning values in Python? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 2

What is the generally preferred way of assigning values in Python?

a, b, c = 1, 2, 3 or a=1 b=2 c=3 What would be use cases where the other method is recommended instead?

1st May 2024, 7:03 AM
Igor Matić
Igor Matić - avatar
5 Respostas
+ 6
Your first example is actually tuple destructuring. The right side is a tuple of 3 elements that can also be written as (1, 2, 3). I would indeed use this format when I want to assign particular elements from a collection in compact form. For example: first, *_, last = [42, 2, 3, 4, 19] print(first, last) Your second example is the most common way, but I recommend to use variable names that are meaningful and describe their purpose. Third option if you want to assign the same value to all: a = b = c = 1 And fourth option is using the := walrus operator, if you want to perform the assignment and use the same value in the same context.
1st May 2024, 9:17 AM
Tibor Santa
Tibor Santa - avatar
+ 7
Igor Matić , we can also have some other ways of assigning values to variables. this is helpful when user can give inputs. see sample in attached file. https://sololearn.com/compiler-playground/c9ExI3Htp0o3/?ref=app
1st May 2024, 7:40 PM
Lothar
Lothar - avatar
+ 4
Both methods achieve the same result in Python, but using multiple assignment (the first method) is often preferred when you're assigning values to multiple variables that are related in some way. This can make the code more concise and easier to read, especially when the variables have a clear relationship or are part of a pattern. On the other hand, separate assignment (the second method) might be preferred when you need to perform additional operations or logic between the assignments, or when you want to add comments or documentation to each individual assignment. It can also be more readable when the variable assignments are not closely related or part of a pattern.
1st May 2024, 8:47 AM
knara harutyunova
knara harutyunova - avatar
+ 4
Unlike other languages, in Python this is very simple. We don't need to declare a variable, all we need to do is give it a name, put the equal sign = and then the value that we want to assign. That's it.
1st May 2024, 8:49 AM
JaScript
JaScript - avatar
+ 2
It depends. sometimes you need to do a = 4 or a: int a = 4 or a, b = 4, 1, 2, 3
1st May 2024, 8:57 PM
White Shadow
White Shadow - avatar