python python-3.x

Python multiple variables on left side of assignment operator

Could someone please explain the concept of having a comma delimited chain (probably not the correct terminology, but I didn’t want to confuse it with list) of variable names on the left side of the assignment operator?

What I’m referring to would be something of the following nature

reader = csv.reader(open('some_file', 'rb'))
for row in reader:
k, v = row
myDictionary[k] = v

I know that example might lead to the question of the format of ‘some_file’, so here is another example I’ve come across

username, password = sys.argv[1:]

I understand that argv comes from the command line, and 1: refers to all arguments after the python script name, but how do username and password get the correct items? In other words, what delimits the arguments passed into this program, is it just the space between the arguments?

In reference to the first example, how do k and v get their values from row, assuming row is a two column line. Do those use the comma as the delimiter?

Any explanation and/or links to Python code or documentation would be great.

k, v = row


username, password = sys.argv[1:]

are examples of sequence unpacking. Sequence unpacking requires the number of variables on the left hand side of the assignment operator to have the same number of elements as the sequence on the right. If they do the first element of the sequence is assigned to the first variable, the second to the second and so on. If they are not equal it will throw a value error.

str, unicode, list, tuple, bytearray, buffer, xrange are all valid sequences and can be used on the right hand side of the operator.

All that is left to understand is whether ‘row’ and sys.argv[1:] are valid sequences with 2 elements.

csv.reader() returns each row of the csv as a list of strings. So it is a valid sequence. If the csv has 2 columns the list will have 2 elements. By default csv.reader uses a comma as the delimeter to split on. You can specify a different delimiter if required:

csv.reader(csv_file, delimiter="|")

For every invocation of Python, sys.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. So again a valid sequence. argv[0] is always the script name. So if the user ran the program with 2 arguments, a username followed by a password sys.argv[1:] would be a list of 2 elements as required.