Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a=b=c in python? [duplicate]

I am quite confused, consecutive equal = can be used in python like:

a = b = c

What is this language feature called? Is there something I can read about that?

Can it be generated into 4 equals?

a = b = c = d
like image 506
Hello lad Avatar asked Dec 03 '14 12:12

Hello lad


People also ask

What is a B C Python?

Python allows you to assign a single value to several variables simultaneously. For example: a = b = c = 1. Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location.

Is a/b/c valid in Python?

With those languages, a<b would evaluate to a boolean and continuing the evaluation, b<c , would be invalid since it would attempt to evaluate a boolean against a number (most likely throwing a compile time error or falsifying the intended comparison).

What is the difference between AB and AB in Python?

For mutable types such as list , the result of a = b[:] will be identical to a[:] = b , in that a will be a shallow copy of b ; for immutable types such as tuple , a[:] = b is invalid. For badly-behaved user-defined types, all bets are off.

How do you define a double variable in Python?

Python does not have an inbuilt double data type, but it has a float type that designates a floating-point number. You can count double in Python as float values which are specified with a decimal point. All platforms represent Python float values as 64-bit “double-precision” values, according to the IEEE 754 standard.


1 Answers

This is just a way to declare a and b as equal to c.

>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2

So you can use as much as you want:

>>> i=7
>>> a=b=c=d=e=f=g=h=i

You can read more in Multiple Assignment from this Python tutorial.

Python allows you to assign a single value to several variables simultaneously. For example:

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

a, b, c = 1, 2, "john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.


There is also another fancy thing! You can swap values like this: a,b=b,a:

>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2
like image 60
fedorqui 'SO stop harming' Avatar answered Oct 25 '22 19:10

fedorqui 'SO stop harming'