O. San
O. San

Reputation: 1177

What does a comma do in a python assignment

I have basic knowledge in c++ and I got an assignment to read a code it python and rewrite it in c++. I'm not familiar with python so I'm sorry for any newbie Q :).

In the code I see:

before,err = TG.quad(fnx, -N/2, -x)
before_n = before/all

inTime, err = TG.quad(fnx, -x,left)
inTime_n= inTime/all

in the first line, are 'before' and 'err' 2 vars who are assigned to the value from the left?

when I try to run an example for myself:

b,a= 5
print (a,b)

I get the error

"TypeError: 'int' object is not iterable",

what am I missing?

Upvotes: 0

Views: 2735

Answers (3)

Lucas
Lucas

Reputation: 7331

Short answer:

It is simply a shorter way of assigning variables.

a, b = 1, 2

Is the same as:

a = 1
b = 2

More technical: As TigerhawkT3 says, they are not exactly the same. For example in:

a = 0
b = 1

a, b = b, a

a is 1 and b is 0, Exchanging the values of a and b. This is different from

a = b
b = a

Where a and b are 1.

On the other hand, if we do:

x = [0, 1]
i = 0
i, x[i] = 1, 2

x is [0, 2]. First assign i, then x[i].

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

This is covered in the official Python tutorial, under Data Structures > Tuples and Sequences:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

Note this portion:

Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

The statement before,err = TG.quad(fnx, -N/2, -x) fulfills this requirement, but b,a = 5 does not.

Upvotes: 4

minchan Jun
minchan Jun

Reputation: 47

You should have two values for each variables.

b,a= 5,5
print (a,b)

I am sure your method is returning two values.

Upvotes: 2

Related Questions