Simultaneous Assignment

There is an alternative form of the assignment statement that allows us to calculate several values all at the same time. It looks like this:

<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>

This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example.

Here sum would get the sum of x and y and diff would get the difference.

This form of assignment seems strange at first, but it can prove remarkably useful. Here's an example. Suppose you have two variables x and y and you want to swap the values. That is, you want the value currently stored in x to be in y and the value that is currently in y to be stored in x. At first, you might think this could be done with two simple assignments.

This doesn't work. We can trace the execution of these statements step-by-step to see why.

Suppose x and y start with the values 2 and 4. Let's examine the logic of the program to see how the variables change. The following sequence uses comments to describe what happens to the variables as these two statements are executed.

# variables x y

# initial values 2 4 x=y

# final 4 4

See how the first statement clobbers the assign x to y in the second step, we just One way to make the swap work is original value of x.

Let's walk-through this sequence to see how it works.

# variables x y temp

# initial values 2 4 no value yet temp = x

As you can see from the final values of x and y, the swap was successful in this case.

This sort of three-way shuffle is common in other programming languages. In Python, the simultaneous assignment statement offers an elegant alternative. Here is a simpler Python equivalent:

original value of x by assigning to it the value of y? When we then end up with two copies of the original y value.

to introduce an additional variable that temporarily remembers the x, y = y, x

Because the assignment is simultaneous, it avoids wiping out one of the original values.

Simultaneous assignment can also be used to get multiple values from the user in a single input. Consider this program for averaging exam scores:

# A simple program to average two exam scores

# Illustrates use of multiple input def main():

print "This program computes the average of two exam scores."

score1, score2 = input("Enter two scores separated by a comma: ") average = (scorei + score2) / 2.0

print "The average of the scores is:", average main()

The program prompts for two scores separated by a comma. Suppose the user types 86, 92. The effect of the input statement is then the same as if we had done this assignment:

We have gotten a value for each of the variables in one fell swoop. This example used just two values, but it could be generalized to any number of inputs.

Of course, we could have just gotten the input from the user using separate input statements.

score1 = input("Enter the first score: ") score2 = input("Enter the second score: ")

In some ways this may be better, as the separate prompts are more informative for the user. In this example the decision as to which approach to take is largely a matter of taste. Sometimes getting multiple values in a single input provides a more intuitive user interface, so it is nice technique to have in your toolkit.

Continue reading here: Using the Math Library

Was this article helpful?

Related Posts

  • Exercises - Python Programming
  • Assignment Statements - Python Object Oriented Programming
  • Graphics Programming - Python Programming
  • Interactive Graphics - Python Programming
  • Indefinite Loops - Python Programming

Readers' Questions

What is the simultaneous assignment?
Simultaneous assignment is a programming language feature that allows multiple variables to be assigned values at the same time. It is typically used when multiple variables need to be set to the same value, typically the result of an expression.
What are simultaneous assignments in python?
Simultaneous assignments are a type of assignment in Python that allows you to assign multiple variables at once. It is a way of assigning multiple variables their values in one line of code. This can make the code more concise and easier to read. The syntax for a simultaneous assignment is var1, var2, ..., varn = expression.

Python's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Table of Contents

The Assignment Statement Syntax

The assignment operator, assignments and variables, other assignment syntax, initializing and updating variables, making multiple variables refer to the same object, updating lists through indices and slices, adding and updating dictionary keys, doing parallel assignments, unpacking iterables, providing default argument values, augmented mathematical assignment operators, augmented assignments for concatenation and repetition, augmented bitwise assignment operators, annotated assignment statements, assignment expressions with the walrus operator, managed attribute assignments, define or call a function, work with classes, import modules and objects, use a decorator, access the control variable in a for loop or a comprehension, use the as keyword, access the _ special variable in an interactive session, built-in objects, named constants.

Python’s assignment operators allow you to define assignment statements . This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables , built-in data types , comprehensions , functions , and Python keywords . Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming , constants , imports , type hints , properties , descriptors , and decorators .

Free Source Code: Click here to download the free assignment operator source code that you’ll use to write assignment statements that allow you to create, initialize, and update variables in your code.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables . In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

To create a new variable or to update the value of an existing one in Python, you’ll use an assignment statement . This statement has the following three components:

  • A left operand, which must be a variable
  • The assignment operator ( = )
  • A right operand, which can be a concrete value , an object , or an expression

Here’s how an assignment statement will generally look in Python:

Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal —or an expression that evaluates to a value.

To execute an assignment statement like the above, Python runs the following steps:

  • Evaluate the right-hand expression to produce a concrete value or object . This value will live at a specific memory address in your computer.
  • Store the object’s memory address in the left-hand variable . This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference . In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The central component of an assignment statement is the assignment operator . This operator is represented by the = symbol, which separates two operands:

  • A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical , logical , and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands .

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

Note: Like C , Python uses == for equality comparisons and = for assignments. Unlike C, Python doesn’t allow you to accidentally use the assignment operator ( = ) in an equality comparison.

Equality is a symmetrical relationship, and assignment is not. For example, the expression a == 42 is equivalent to 42 == a . In contrast, the statement a = 42 is correct and legal, while 42 = a isn’t allowed. You’ll learn more about illegal assignments later on.

The right-hand operand in an assignment statement can be any Python object, such as a number , list , string , dictionary , or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

The first two sample assignments in this code snippet use concrete values, also known as literals , to create and initialize number and greeting . The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Note: You can use the built-in id() function to inspect the memory address stored in a given variable.

Here’s a short example of how this function works:

The number in your output represents the memory address stored in number . Through this address, Python can access the content of number , which is the integer 42 in this example.

If you run this code on your computer, then you’ll get a different memory address because this value varies from execution to execution and computer to computer.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  • Creating and initializing new variables
  • Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter . You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names , like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys , like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment . Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.

The most elementary use case of an assignment statement is to create a new variable and initialize it using a particular value or expression:

All these statements create new variables, assigning them initial values or expressions. For an initial value, you should always use the most sensible and least surprising value that you can think of. For example, initializing a counter to something different from 0 may be confusing and unexpected because counters almost always start having counted no objects.

Updating a variable’s current value or state is another common use case of assignment statements. In Python, assigning a new value to an existing variable doesn’t modify the variable’s current value. Instead, it causes the variable to refer to a different value. The previous value will be garbage-collected if no other variable refers to it.

Consider the following examples:

These examples run two consecutive assignments on the same variable. The first one assigns the string "Hello, World!" to a new variable named greeting .

The second assignment updates the value of greeting by reassigning it the "Hi, Pythonistas!" string. In this example, the original value of greeting —the "Hello, World!" string— is lost and garbage-collected. From this point on, you can’t access the old "Hello, World!" string.

Even though running multiple assignments on the same variable during a program’s execution is common practice, you should use this feature with caution. Changing the value of a variable can make your code difficult to read, understand, and debug. To comprehend the code fully, you’ll have to remember all the places where the variable was changed and the sequential order of those changes.

Because assignments also define the data type of their target variables, it’s also possible for your code to accidentally change the type of a given variable at runtime. A change like this can lead to breaking errors, like AttributeError exceptions. Remember that strings don’t have the same methods and attributes as lists or dictionaries, for example.

In Python, you can make several variables reference the same object in a multiple-assignment line. This can be useful when you want to initialize several similar variables using the same initial value:

In this example, you chain two assignment operators in a single line. This way, your two variables refer to the same initial value of 0 . Note how both variables hold the same memory address, so they point to the same instance of 0 .

When it comes to integer variables, Python exhibits a curious behavior. It provides a numeric interval where multiple assignments behave the same as independent assignments. Consider the following examples:

To create n and m , you use independent assignments. Therefore, they should point to different instances of the number 42 . However, both variables hold the same object, which you confirm by comparing their corresponding memory addresses.

Now check what happens when you use a greater initial value:

Now n and m hold different memory addresses, which means they point to different instances of the integer number 300 . In contrast, when you use multiple assignments, both variables refer to the same object. This tiny difference can save you small bits of memory if you frequently initialize integer variables in your code.

The implicit behavior of making independent assignments point to the same integer number is actually an optimization called interning . It consists of globally caching the most commonly used integer values in day-to-day programming.

Under the hood, Python defines a numeric interval in which interning takes place. That’s the interning interval for integer numbers. You can determine this interval using a small script like the following:

This script helps you determine the interning interval by comparing integer numbers from -10 to 500 . If you run the script from your command line, then you’ll get an output like the following:

This output means that if you use a single number between -5 and 256 to initialize several variables in independent statements, then all these variables will point to the same object, which will help you save small bits of memory in your code.

In contrast, if you use a number that falls outside of the interning interval, then your variables will point to different objects instead. Each of these objects will occupy a different memory spot.

You can use the assignment operator to mutate the value stored at a given index in a Python list. The operator also works with list slices . The syntax to write these types of assignment statements is the following:

In the first construct, expression can return any Python object, including another list. In the second construct, expression must return a series of values as a list, tuple, or any other sequence. You’ll get a TypeError if expression returns a single value.

Note: When creating slice objects, you can use up to three arguments. These arguments are start , stop , and step . They define the number that starts the slice, the number at which the slicing must stop retrieving values, and the step between values.

Here’s an example of updating an individual value in a list:

In this example, you update the value at index 2 using an assignment statement. The original number at that index was 7 , and after the assignment, the number is 3 .

Note: Using indices and the assignment operator to update a value in a tuple or a character in a string isn’t possible because tuples and strings are immutable data types in Python.

Their immutability means that you can’t change their items in place :

You can’t use the assignment operator to change individual items in tuples or strings. These data types are immutable and don’t support item assignments.

It’s important to note that you can’t add new values to a list by using indices that don’t exist in the target list:

In this example, you try to add a new value to the end of numbers by using an index that doesn’t exist. This assignment isn’t allowed because there’s no way to guarantee that new indices will be consecutive. If you ever want to add a single value to the end of a list, then use the .append() method.

If you want to update several consecutive values in a list, then you can use slicing and an assignment statement:

In the first example, you update the letters between indices 1 and 3 without including the letter at 3 . The second example updates the letters from index 3 until the end of the list. Note that this slicing appends a new value to the list because the target slice is shorter than the assigned values.

Also note that the new values were provided through a tuple, which means that this type of assignment allows you to use other types of sequences to update your target list.

The third example updates a single value using a slice where both indices are equal. In this example, the assignment inserts a new item into your target list.

In the final example, you use a step of 2 to replace alternating letters with their lowercase counterparts. This slicing starts at index 1 and runs through the whole list, stepping by two items each time.

Updating the value of an existing key or adding new key-value pairs to a dictionary is another common use case of assignment statements. To do these operations, you can use the following syntax:

The first construct helps you update the current value of an existing key, while the second construct allows you to add a new key-value pair to the dictionary.

For example, to update an existing key, you can do something like this:

In this example, you update the current inventory of oranges in your store using an assignment. The left operand is the existing dictionary key, and the right operand is the desired new value.

While you can’t add new values to a list by assignment, dictionaries do allow you to add new key-value pairs using the assignment operator. In the example below, you add a lemon key to inventory :

In this example, you successfully add a new key-value pair to your inventory with 100 units. This addition is possible because dictionaries don’t have consecutive indices but unique keys, which are safe to add by assignment.

The assignment statement does more than assign the result of a single expression to a single variable. It can also cope nicely with assigning multiple values to multiple variables simultaneously in what’s known as a parallel assignment .

Here’s the general syntax for parallel assignments in Python:

Note that the left side of the statement can be either a tuple or a list of variables. Remember that to create a tuple, you just need a series of comma-separated elements. In this case, these elements must be variables.

The right side of the statement must be a sequence or iterable of values or expressions. In any case, the number of elements in the right operand must match the number of variables on the left. Otherwise, you’ll get a ValueError exception.

In the following example, you compute the two solutions of a quadratic equation using a parallel assignment:

In this example, you first import sqrt() from the math module. Then you initialize the equation’s coefficients in a parallel assignment.

The equation’s solution is computed in another parallel assignment. The left operand contains a tuple of two variables, x1 and x2 . The right operand consists of a tuple of expressions that compute the solutions for the equation. Note how each result is assigned to each variable by position.

A classical use case of parallel assignment is to swap values between variables:

The highlighted line does the magic and swaps the values of previous_value and next_value at the same time. Note that in a programming language that doesn’t support this kind of assignment, you’d have to use a temporary variable to produce the same effect:

In this example, instead of using parallel assignment to swap values between variables, you use a new variable to temporarily store the value of previous_value to avoid losing its reference.

For a concrete example of when you’d need to swap values between variables, say you’re learning how to implement the bubble sort algorithm , and you come up with the following function:

In the highlighted line, you use a parallel assignment to swap values in place if the current value is less than the next value in the input list. To dive deeper into the bubble sort algorithm and into sorting algorithms in general, check out Sorting Algorithms in Python .

You can use assignment statements for iterable unpacking in Python. Unpacking an iterable means assigning its values to a series of variables one by one. The iterable must be the right operand in the assignment, while the variables must be the left operand.

Like in parallel assignments, the variables must come as a tuple or list. The number of variables must match the number of values in the iterable. Alternatively, you can use the unpacking operator ( * ) to grab several values in a variable if the number of variables doesn’t match the iterable length.

Here’s the general syntax for iterable unpacking in Python:

Iterable unpacking is a powerful feature that you can use all around your code. It can help you write more readable and concise code. For example, you may find yourself doing something like this:

Whenever you do something like this in your code, go ahead and replace it with a more readable iterable unpacking using a single and elegant assignment, like in the following code snippet:

The numbers list on the right side contains four values. The assignment operator unpacks these values into the four variables on the left side of the statement. The values in numbers get assigned to variables in the same order that they appear in the iterable. The assignment is done by position.

Note: Because Python sets are also iterables, you can use them in an iterable unpacking operation. However, it won’t be clear which value goes to which variable because sets are unordered data structures.

The above example shows the most common form of iterable unpacking in Python. The main condition for the example to work is that the number of variables matches the number of values in the iterable.

What if you don’t know the iterable length upfront? Will the unpacking work? It’ll work if you use the * operator to pack several values into one of your target variables.

For example, say that you want to unpack the first and second values in numbers into two different variables. Additionally, you would like to pack the rest of the values in a single variable conveniently called rest . In this case, you can use the unpacking operator like in the following code:

In this example, first and second hold the first and second values in numbers , respectively. These values are assigned by position. The * operator packs all the remaining values in the input iterable into rest .

The unpacking operator ( * ) can appear at any position in your series of target variables. However, you can only use one instance of the operator:

The iterable unpacking operator works in any position in your list of variables. Note that you can only use one unpacking operator per assignment. Using more than one unpacking operator isn’t allowed and raises a SyntaxError .

Dropping away unwanted values from the iterable is a common use case for the iterable unpacking operator. Consider the following example:

In Python, if you want to signal that a variable won’t be used, then you use an underscore ( _ ) as the variable’s name. In this example, useful holds the only value that you need to use from the input iterable. The _ variable is a placeholder that guarantees that the unpacking works correctly. You won’t use the values that end up in this disposable variable.

Note: In the example above, if your target iterable is a sequence data type, such as a list or tuple, then it’s best to access its last item directly.

To do this, you can use the -1 index:

Using -1 gives you access to the last item of any sequence data type. In contrast, if you’re dealing with iterators , then you won’t be able to use indices. That’s when the *_ syntax comes to your rescue.

The pattern used in the above example comes in handy when you have a function that returns multiple values, and you only need a few of these values in your code. The os.walk() function may provide a good example of this situation.

This function allows you to iterate over the content of a directory recursively. The function returns a generator object that yields three-item tuples. Each tuple contains the following items:

  • The path to the current directory as a string
  • The names of all the immediate subdirectories as a list of strings
  • The names of all the files in the current directory as a list of strings

Now say that you want to iterate over your home directory and list only the files. You can do something like this:

This code will issue a long output depending on the current content of your home directory. Note that you need to provide a string with the path to your user folder for the example to work. The _ placeholder variable will hold the unwanted data.

In contrast, the filenames variable will hold the list of files in the current directory, which is the data that you need. The code will print the list of filenames. Go ahead and give it a try!

The assignment operator also comes in handy when you need to provide default argument values in your functions and methods. Default argument values allow you to define functions that take arguments with sensible defaults. These defaults allow you to call the function with specific values or to simply rely on the defaults.

As an example, consider the following function:

This function takes one argument, called name . This argument has a sensible default value that’ll be used when you call the function without arguments. To provide this sensible default value, you use an assignment.

Note: According to PEP 8 , the style guide for Python code, you shouldn’t use spaces around the assignment operator when providing default argument values in function definitions.

Here’s how the function works:

If you don’t provide a name during the call to greet() , then the function uses the default value provided in the definition. If you provide a name, then the function uses it instead of the default one.

Up to this point, you’ve learned a lot about the Python assignment operator and how to use it for writing different types of assignment statements. In the following sections, you’ll dive into a great feature of assignment statements in Python. You’ll learn about augmented assignments .

Augmented Assignment Operators in Python

Python supports what are known as augmented assignments . An augmented assignment combines the assignment operator with another operator to make the statement more concise. Most Python math and bitwise operators have an augmented assignment variation that looks something like this:

Note that $ isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. This statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the = sign, using the previous value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

In practice, an augmented assignment like the above is equivalent to the following statement:

As you can conclude, augmented assignments are syntactic sugar . They provide a shorthand notation for a specific and popular kind of assignment.

For example, say that you need to define a counter variable to count some stuff in your code. You can use the += operator to increment counter by 1 using the following code:

In this example, the += operator, known as augmented addition , adds 1 to the previous value in counter each time you run the statement counter += 1 .

It’s important to note that unlike regular assignments, augmented assignments don’t create new variables. They only allow you to update existing variables. If you use an augmented assignment with an undefined variable, then you get a NameError :

Python evaluates the right side of the statement before assigning the resulting value back to the target variable. In this specific example, when Python tries to compute x + 1 , it finds that x isn’t defined.

Great! You now know that an augmented assignment consists of combining the assignment operator with another operator, like a math or bitwise operator. To continue this discussion, you’ll learn which math operators have an augmented variation in Python.

An equation like x = x + b doesn’t make sense in math. But in programming, a statement like x = x + b is perfectly valid and can be extremely useful. It adds b to x and reassigns the result back to x .

As you already learned, Python provides an operator to shorten x = x + b . Yes, the += operator allows you to write x += b instead. Python also offers augmented assignment operators for most math operators. Here’s a summary:

Operator Description Example Equivalent
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

The Example column provides generic examples of how to use the operators in actual code. Note that x must be previously defined for the operators to work correctly. On the other hand, y can be either a concrete value or an expression that returns a value.

Note: The matrix multiplication operator ( @ ) doesn’t support augmented assignments yet.

Consider the following example of matrix multiplication using NumPy arrays:

Note that the exception traceback indicates that the operation isn’t supported yet.

To illustrate how augmented assignment operators work, say that you need to create a function that takes an iterable of numeric values and returns their sum. You can write this function like in the code below:

In this function, you first initialize total to 0 . In each iteration, the loop adds a new number to total using the augmented addition operator ( += ). When the loop terminates, total holds the sum of all the input numbers. Variables like total are known as accumulators . The += operator is typically used to update accumulators.

Note: Computing the sum of a series of numeric values is a common operation in programming. Python provides the built-in sum() function for this specific computation.

Another interesting example of using an augmented assignment is when you need to implement a countdown while loop to reverse an iterable. In this case, you can use the -= operator:

In this example, custom_reversed() is a generator function because it uses yield . Calling the function creates an iterator that yields items from the input iterable in reverse order. To decrement the control variable, index , you use an augmented subtraction statement that subtracts 1 from the variable in every iteration.

Note: Similar to summing the values in an iterable, reversing an iterable is also a common requirement. Python provides the built-in reversed() function for this specific computation, so you don’t have to implement your own. The above example only intends to show the -= operator in action.

Finally, counters are a special type of accumulators that allow you to count objects. Here’s an example of a letter counter:

To create this counter, you use a Python dictionary. The keys store the letters. The values store the counts. Again, to increment the counter, you use an augmented addition.

Counters are so common in programming that Python provides a tool specially designed to facilitate the task of counting. Check out Python’s Counter: The Pythonic Way to Count Objects for a complete guide on how to use this tool.

The += and *= augmented assignment operators also work with sequences , such as lists, tuples, and strings. The += operator performs augmented concatenations , while the *= operator performs augmented repetition .

These operators behave differently with mutable and immutable data types:

Operator Description Example
Runs an augmented concatenation operation on the target sequence. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.
Adds to itself times. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator operates on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Consider the following examples and pay attention to the result of calling the id() function:

Mutable sequences like lists support the += augmented assignment operator through the .__iadd__() method, which performs an in-place addition. This method mutates the underlying list, appending new values to its end.

Note: If the left operand is mutable, then x += y may not be completely equivalent to x = x + y . For example, if you do list_1 = list_1 + list_2 instead of list_1 += list_2 above, then you’ll create a new list instead of mutating the existing one. This may be important if other variables refer to the same list.

Immutable sequences, such as tuples and strings, don’t provide an .__iadd__() method. Therefore, augmented concatenations fall back to the .__add__() method, which doesn’t modify the sequence in place but returns a new sequence.

There’s another difference between mutable and immutable sequences when you use them in an augmented concatenation. Consider the following examples:

With mutable sequences, the data to be concatenated can come as a list, tuple, string, or any other iterable. In contrast, with immutable sequences, the data can only come as objects of the same type. You can concatenate tuples to tuples and strings to strings, for example.

Again, the augmented repetition operator works with a sequence on the left side of the operator and an integer on the right side. This integer value represents the number of repetitions to get in the resulting sequence:

When the *= operator operates on a mutable sequence, it falls back to the .__imul__() method, which performs the operation in place, modifying the underlying sequence. In contrast, if *= operates on an immutable sequence, then .__mul__() is called, returning a new sequence of the same type.

Note: Values of n less than 0 are treated as 0 , which returns an empty sequence of the same data type as the target sequence on the left side of the *= operand.

Note that a_list[0] is a_list[3] returns True . This is because the *= operator doesn’t make a copy of the repeated data. It only reflects the data. This behavior can be a source of issues when you use the operator with mutable values.

For example, say that you want to create a list of lists to represent a matrix, and you need to initialize the list with n empty lists, like in the following code:

In this example, you use the *= operator to populate matrix with three empty lists. Now check out what happens when you try to populate the first sublist in matrix :

The appended values are reflected in the three sublists. This happens because the *= operator doesn’t make copies of the data that you want to repeat. It only reflects the data. Therefore, every sublist in matrix points to the same object and memory address.

If you ever need to initialize a list with a bunch of empty sublists, then use a list comprehension :

This time, when you populate the first sublist of matrix , your changes aren’t propagated to the other sublists. This is because all the sublists are different objects that live in different memory addresses.

Bitwise operators also have their augmented versions. The logic behind them is similar to that of the math operators. The following table summarizes the augmented bitwise operators that Python provides:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

The augmented bitwise assignment operators perform the intended operation by taking the current value of the left operand as a starting point for the computation. Consider the following example, which uses the & and &= operators:

Programmers who work with high-level languages like Python rarely use bitwise operations in day-to-day coding. However, these types of operations can be useful in some situations.

For example, say that you’re implementing a Unix-style permission system for your users to access a given resource. In this case, you can use the characters "r" for reading, "w" for writing, and "x" for execution permissions, respectively. However, using bit-based permissions could be more memory efficient:

You can assign permissions to your users with the OR bitwise operator or the augmented OR bitwise operator. Finally, you can use the bitwise AND operator to check if a user has a certain permission, as you did in the final two examples.

You’ve learned a lot about augmented assignment operators and statements in this and the previous sections. These operators apply to math, concatenation, repetition, and bitwise operations. Now you’re ready to look at other assignment variants that you can use in your code or find in other developers’ code.

Other Assignment Variants

So far, you’ve learned that Python’s assignment statements and the assignment operator are present in many different scenarios and use cases. Those use cases include variable creation and initialization, parallel assignments, iterable unpacking, augmented assignments, and more.

In the following sections, you’ll learn about a few variants of assignment statements that can be useful in your future coding. You can also find these assignment variants in other developers’ code. So, you should be aware of them and know how they work in practice.

In short, you’ll learn about:

  • Annotated assignment statements with type hints
  • Assignment expressions with the walrus operator
  • Managed attribute assignments with properties and descriptors
  • Implicit assignments in Python

These topics will take you through several interesting and useful examples that showcase the power of Python’s assignment statements.

PEP 526 introduced a dedicated syntax for variable annotation back in Python 3.6 . The syntax consists of the variable name followed by a colon ( : ) and the variable type:

Even though these statements declare three variables with their corresponding data types, the variables aren’t actually created or initialized. So, for example, you can’t use any of these variables in an augmented assignment statement:

If you try to use one of the previously declared variables in an augmented assignment, then you get a NameError because the annotation syntax doesn’t define the variable. To actually define it, you need to use an assignment.

The good news is that you can use the variable annotation syntax in an assignment statement with the = operator:

The first statement in this example is what you can call an annotated assignment statement in Python. You may ask yourself why you should use type annotations in this type of assignment if everybody can see that counter holds an integer number. You’re right. In this example, the variable type is unambiguous.

However, imagine what would happen if you found a variable initialization like the following:

What would be the data type of each user in users ? If the initialization of users is far away from the definition of the User class, then there’s no quick way to answer this question. To clarify this ambiguity, you can provide the appropriate type hint for users :

Now you’re clearly communicating that users will hold a list of User instances. Using type hints in assignment statements that initialize variables to empty collection data types—such as lists, tuples, or dictionaries—allows you to provide more context about how your code works. This practice will make your code more explicit and less error-prone.

Up to this point, you’ve learned that regular assignment statements with the = operator don’t have a return value. They just create or update variables. Therefore, you can’t use a regular assignment to assign a value to a variable within the context of an expression.

Python 3.8 changed this by introducing a new type of assignment statement through PEP 572 . This new statement is known as an assignment expression or named expression .

Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have a return value, which isn’t the case with all types of statements.

Unlike regular assignments, assignment expressions have a return value, which is why they’re called expressions in the first place. This return value is automatically assigned to a variable. To write an assignment expression, you must use the walrus operator ( := ), which was named for its resemblance to the eyes and tusks of a walrus lying on its side.

The general syntax of an assignment statement is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, there are certain situations in which these parentheses are superfluous. Either way, they won’t hurt you.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand.

Note: Assignment expressions with the walrus operator have several practical use cases. They also have a few restrictions. For example, they’re illegal in certain contexts, such as lambda functions, parallel assignments, and augmented assignments.

For a deep dive into this special type of assignment, check out The Walrus Operator: Python 3.8 Assignment Expressions .

A particularly handy use case for assignment expressions is when you need to grab the result of an expression used in the context of a conditional statement. For example, say that you need to write a function to compute the mean of a sample of numeric values. Without the walrus operator, you could do something like this:

In this example, the sample size ( n ) is a value that you need to reuse in two different computations. First, you need to check whether the sample has data points or not. Then you need to use the sample size to compute the mean. To be able to reuse n , you wrote a dedicated assignment statement at the beginning of your function to grab the sample size.

You can avoid this extra step by combining it with the first use of the target value, len(sample) , using an assignment expression like the following:

The assignment expression introduced in the conditional computes the sample size and assigns it to n . This way, you guarantee that you have a reference to the sample size to use in further computations.

Because the assignment expression returns the sample size anyway, the conditional can check whether that size equals 0 or not and then take a certain course of action depending on the result of this check. The return statement computes the sample’s mean and sends the result back to the function caller.

Python provides a few tools that allow you to fine-tune the operations behind the assignment of attributes. The attributes that run implicit operations on assignments are commonly referred to as managed attributes .

Properties are the most commonly used tool for providing managed attributes in your classes. However, you can also use descriptors and, in some cases, the .__setitem__() special method.

To understand what fine-tuning the operation behind an assignment means, say that you need a Point class that only allows numeric values for its coordinates, x and y . To write this class, you must set up a validation mechanism to reject non-numeric values. You can use properties to attach the validation functionality on top of x and y .

Here’s how you can write your class:

In Point , you use properties for the .x and .y coordinates. Each property has a getter and a setter method . The getter method returns the attribute at hand. The setter method runs the input validation using a try … except block and the built-in float() function. Then the method assigns the result to the actual attribute.

Here’s how your class works in practice:

When you use a property-based attribute as the left operand in an assignment statement, Python automatically calls the property’s setter method, running any computation from it.

Because both .x and .y are properties, the input validation runs whenever you assign a value to either attribute. In the first example, the input values are valid numbers and the validation passes. In the final example, "one" isn’t a valid numeric value, so the validation fails.

If you look at your Point class, you’ll note that it follows a repetitive pattern, with the getter and setter methods looking quite similar. To avoid this repetition, you can use a descriptor instead of a property.

A descriptor is a class that implements the descriptor protocol , which consists of four special methods :

  • .__get__() runs when you access the attribute represented by the descriptor.
  • .__set__() runs when you use the attribute in an assignment statement.
  • .__delete__() runs when you use the attribute in a del statement.
  • .__set_name__() sets the attribute’s name, creating a name-aware attribute.

Here’s how your code may look if you use a descriptor to represent the coordinates of your Point class:

You’ve removed repetitive code by defining Coordinate as a descriptor that manages the input validation in a single place. Go ahead and run the following code to try out the new implementation of Point :

Great! The class works as expected. Thanks to the Coordinate descriptor, you now have a more concise and non-repetitive version of your original code.

Another way to fine-tune the operations behind an assignment statement is to provide a custom implementation of .__setitem__() in your class. You’ll use this method in classes representing mutable data collections, such as custom list-like or dictionary-like classes.

As an example, say that you need to create a dictionary-like class that stores its keys in lowercase letters:

In this example, you create a dictionary-like class by subclassing UserDict from collections . Your class implements a .__setitem__() method, which takes key and value as arguments. The method uses str.lower() to convert key into lowercase letters before storing it in the underlying dictionary.

Python implicitly calls .__setitem__() every time you use a key as the left operand in an assignment statement. This behavior allows you to tweak how you process the assignment of keys in your custom dictionary.

Implicit Assignments in Python

Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors.

Whenever you complete an action in the following list, Python runs an implicit assignment for you:

  • Define or call a function
  • Define or instantiate a class
  • Use the current instance , self
  • Import modules and objects
  • Use a decorator
  • Use the control variable in a for loop or a comprehension
  • Use the as qualifier in with statements , imports, and try … except blocks
  • Access the _ special variable in an interactive session

Behind the scenes, Python performs an assignment in every one of the above situations. In the following subsections, you’ll take a tour of all these situations.

When you define a function, the def keyword implicitly assigns a function object to your function’s name. Here’s an example:

From this point on, the name greet refers to a function object that lives at a given memory address in your computer. You can call the function using its name and a pair of parentheses with appropriate arguments. This way, you can reuse greet() wherever you need it.

If you call your greet() function with fellow as an argument, then Python implicitly assigns the input argument value to the name parameter on the function’s definition. The parameter will hold a reference to the input arguments.

When you define a class with the class keyword, you’re assigning a specific name to a class object . You can later use this name to create instances of that class. Consider the following example:

In this example, the name User holds a reference to a class object, which was defined in __main__.User . Like with a function, when you call the class’s constructor with the appropriate arguments to create an instance, Python assigns the arguments to the parameters defined in the class initializer .

Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you instantiate a class. Thanks to this implicit assignment, you can access .name and .job from within the class without getting a NameError in your code.

Import statements are another variant of implicit assignments in Python. Through an import statement, you assign a name to a module object, class, function, or any other imported object. This name is then created in your current namespace so that you can access it later in your code:

In this example, you import the sys module object from the standard library and assign it to the sys name, which is now available in your namespace, as you can conclude from the second call to the built-in dir() function.

You also run an implicit assignment when you use a decorator in your code. The decorator syntax is just a shortcut for a formal assignment like the following:

Here, you call decorator() with a function object as an argument. This call will typically add functionality on top of the existing function, func() , and return a function object, which is then reassigned to the func name.

The decorator syntax is syntactic sugar for replacing the previous assignment, which you can now write as follows:

Even though this new code looks pretty different from the above assignment, the code implicitly runs the same steps.

Another situation in which Python automatically runs an implicit assignment is when you use a for loop or a comprehension. In both cases, you can have one or more control variables that you then use in the loop or comprehension body:

The memory address of control_variable changes on each iteration of the loop. This is because Python internally reassigns a new value from the loop iterable to the loop control variable on each cycle.

The same behavior appears in comprehensions:

In the end, comprehensions work like for loops but use a more concise syntax. This comprehension creates a new list of strings that mimic the output from the previous example.

The as keyword in with statements, except clauses, and import statements is another example of an implicit assignment in Python. This time, the assignment isn’t completely implicit because the as keyword provides an explicit way to define the target variable.

In a with statement, the target variable that follows the as keyword will hold a reference to the context manager that you’re working with. As an example, say that you have a hello.txt file with the following content:

You want to open this file and print each of its lines on your screen. In this case, you can use the with statement to open the file using the built-in open() function.

In the example below, you accomplish this. You also add some calls to print() that display information about the target variable defined by the as keyword:

This with statement uses the open() function to open hello.txt . The open() function is a context manager that returns a text file object represented by an io.TextIOWrapper instance.

Since you’ve defined a hello target variable with the as keyword, now that variable holds a reference to the file object itself. You confirm this by printing the object and its memory address. Finally, the for loop iterates over the lines and prints this content to the screen.

When it comes to using the as keyword in the context of an except clause, the target variable will contain an exception object if any exception occurs:

In this example, you run a division that raises a ZeroDivisionError . The as keyword assigns the raised exception to error . Note that when you print the exception object, you get only the message because exceptions have a custom .__str__() method that supports this behavior.

There’s a final detail to remember when using the as specifier in a try … except block like the one in the above example. Once you leave the except block, the target variable goes out of scope , and you can’t use it anymore.

Finally, Python’s import statements also support the as keyword. In this context, you can use as to import objects with a different name:

In these examples, you use the as keyword to import the numpy package with the np name and pandas with the name pd . If you call dir() , then you’ll realize that np and pd are now in your namespace. However, the numpy and pandas names are not.

Using the as keyword in your imports comes in handy when you want to use shorter names for your objects or when you need to use different objects that originally had the same name in your code. It’s also useful when you want to make your imported names non-public using a leading underscore, like in import sys as _sys .

The final implicit assignment that you’ll learn about in this tutorial only occurs when you’re using Python in an interactive session. Every time you run a statement that returns a value, the interpreter stores the result in a special variable denoted by a single underscore character ( _ ).

You can access this special variable as you’d access any other variable:

These examples cover several situations in which Python internally uses the _ variable. The first two examples evaluate expressions. Expressions always have a return value, which is automatically assigned to the _ variable every time.

When it comes to function calls, note that if your function returns a fruitful value, then _ will hold it. In contrast, if your function returns None , then the _ variable will remain untouched.

The next example consists of a regular assignment statement. As you already know, regular assignments don’t return any value, so the _ variable isn’t updated after these statements run. Finally, note that accessing a variable in an interactive session returns the value stored in the target variable. This value is then assigned to the _ variable.

Note that since _ is a regular variable, you can use it in other expressions:

In this example, you first create a list of values. Then you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the mean of your list of values.

Now that you’ve learned about some of the implicit assignments that Python runs under the hood, it’s time to dig into a final assignment-related topic. In the following few sections, you’ll learn about some illegal and dangerous assignments that you should be aware of and avoid in your code.

Illegal and Dangerous Assignments in Python

In Python, you’ll find a few situations in which using assignments is either forbidden or dangerous. You must be aware of these special situations and try to avoid them in your code.

In the following sections, you’ll learn when using assignment statements isn’t allowed in Python. You’ll also learn about some situations in which using assignments should be avoided if you want to keep your code consistent and robust.

You can’t use Python keywords as variable names in assignment statements. This kind of assignment is explicitly forbidden. If you try to use a keyword as a variable name in an assignment, then you get a SyntaxError :

Whenever you try to use a keyword as the left operand in an assignment statement, you get a SyntaxError . Keywords are an intrinsic part of the language and can’t be overridden.

If you ever feel the need to name one of your variables using a Python keyword, then you can append an underscore to the name of your variable:

In this example, you’re using the desired name for your variables. Because you added a final underscore to the names, Python doesn’t recognize them as keywords, so it doesn’t raise an error.

Note: Even though adding an underscore at the end of a name is an officially recommended practice , it can be confusing sometimes. Therefore, try to find an alternative name or use a synonym whenever you find yourself using this convention.

For example, you can write something like this:

In this example, using the name booking_class for your variable is way clearer and more descriptive than using class_ .

You’ll also find that you can use only a few keywords as part of the right operand in an assignment statement. Those keywords will generally define simple statements that return a value or object. These include lambda , and , or , not , True , False , None , in , and is . You can also use the for keyword when it’s part of a comprehension and the if keyword when it’s used as part of a ternary operator .

In an assignment, you can never use a compound statement as the right operand. Compound statements are those that require an indented block, such as for and while loops, conditionals, with statements, try … except blocks, and class or function definitions.

Sometimes, you need to name variables, but the desired or ideal name is already taken and used as a built-in name. If this is your case, think harder and find another name. Don’t shadow the built-in.

Shadowing built-in names can cause hard-to-identify problems in your code. A common example of this issue is using list or dict to name user-defined variables. In this case, you override the corresponding built-in names, which won’t work as expected if you use them later in your code.

Consider the following example:

The exception in this example may sound surprising. How come you can’t use list() to build a list from a call to map() that returns a generator of square numbers?

By using the name list to identify your list of numbers, you shadowed the built-in list name. Now that name points to a list object rather than the built-in class. List objects aren’t callable, so your code no longer works.

In Python, you’ll have nothing that warns against using built-in, standard-library, or even relevant third-party names to identify your own variables. Therefore, you should keep an eye out for this practice. It can be a source of hard-to-debug errors.

In programming, a constant refers to a name associated with a value that never changes during a program’s execution. Unlike other programming languages, Python doesn’t have a dedicated syntax for defining constants. This fact implies that Python doesn’t have constants in the strict sense of the word.

Python only has variables. If you need a constant in Python, then you’ll have to define a variable and guarantee that it won’t change during your code’s execution. To do that, you must avoid using that variable as the left operand in an assignment statement.

To tell other Python programmers that a given variable should be treated as a constant, you must write your variable’s name in capital letters with underscores separating the words. This naming convention has been adopted by the Python community and is a recommendation that you’ll find in the Constants section of PEP 8 .

In the following examples, you define some constants in Python:

The problem with these constants is that they’re actually variables. Nothing prevents you from changing their value during your code’s execution. So, at any time, you can do something like the following:

These assignments modify the value of two of your original constants. Python doesn’t complain about these changes, which can cause issues later in your code. As a Python developer, you must guarantee that named constants in your code remain constant.

The only way to do that is never to use named constants in an assignment statement other than the constant definition.

You’ve learned a lot about Python’s assignment operators and how to use them for writing assignment statements . With this type of statement, you can create, initialize, and update variables according to your needs. Now you have the required skills to fully manage the creation and mutation of variables in your Python code.

In this tutorial, you’ve learned how to:

  • Write assignment statements using Python’s assignment operators
  • Work with augmented assignments in Python
  • Explore assignment variants, like assignment expression and managed attributes
  • Identify illegal and dangerous assignments in Python

Learning about the Python assignment operator and how to use it in assignment statements is a fundamental skill in Python. It empowers you to write reliable and effective Python code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python's Assignment Operator: Write Robust Assignments (Source Code)

🔒 No spam. We take your privacy seriously.

python simultaneous assignment

Mastering Python – An Ultimate Guide to Assigning Multiple Variables in Python

Introduction.

Assigning multiple variables is a fundamental concept in Python programming. It allows you to efficiently assign values to multiple variables in a single line of code. Mastering this concept is crucial for writing clean and concise code, as it simplifies complex assignments and improves code readability.

python simultaneous assignment

Basics of assigning multiple variables in Python

In Python, there are two common techniques for assigning multiple variables – unpacking and simultaneous assignment.

Using the unpacking technique

The unpacking technique involves assigning the values of an iterable object, such as a tuple or a list, to individual variables. This technique simplifies the assignment process and saves you from writing multiple assignment statements.

To unpack variables in Python, you can use the following syntax:

{% raw %}variable1, variable2, variable3 = iterable_object{% endraw %}

Here’s an example of unpacking variables in Python:

{% raw %}>>> x, y, z = (1, 2, 3) >>> print(x, y, z) 1 2 3{% endraw %}

Simultaneous assignment of variables

Simultaneous assignment allows you to assign values to multiple variables in a single line of code. This technique is a shorthand way of assigning values to variables without the need for an iterable object.

The syntax for simultaneous assignment is as follows:

{% raw %}variable1 = value1 variable2 = value2 variable3 = value3{% endraw %}

Here’s an example of simultaneous assignment in Python:

{% raw %}>>> x = 1 >>> y = 2 >>> z = 3 >>> print(x, y, z) 1 2 3{% endraw %}

Advanced techniques for assigning multiple variables in Python

Python offers several advanced techniques for assigning multiple variables, including tuple unpacking, list unpacking, and dictionary unpacking.

Tuple unpacking

Tuples are immutable sequences in Python that can be used to store multiple values. Tuple unpacking involves assigning the values of a tuple to multiple variables.

To unpack tuples in Python, you can use the following syntax:

{% raw %}variable1, variable2 = tuple{% endraw %}

Here’s an example of tuple unpacking in Python:

{% raw %}>>> x, y = (1, 2) >>> print(x, y) 1 2{% endraw %}

List unpacking

Lists are mutable sequences in Python that can also be used to store multiple values. List unpacking involves assigning the values of a list to multiple variables.

To unpack lists in Python, you can use the following syntax:

{% raw %}variable1, variable2 = list{% endraw %}

Here’s an example of list unpacking in Python:

{% raw %}>>> x, y = [1, 2] >>> print(x, y) 1 2{% endraw %}

Dictionary unpacking

Dictionaries are key-value pairs in Python that can be used to store multiple values. Dictionary unpacking involves assigning the values of a dictionary to multiple variables.

To unpack dictionaries in Python, you can use the following syntax:

{% raw %}variable1, variable2 = dictionary.values(){% endraw %}

Here’s an example of dictionary unpacking in Python:

{% raw %}>>> x, y = {'a': 1, 'b': 2}.values() >>> print(x, y) 1 2{% endraw %}

Best practices for assigning multiple variables in Python

When assigning multiple variables in Python, it’s important to follow some best practices to ensure clean and maintainable code.

Choosing meaningful variable names

When assigning multiple variables, it’s essential to choose variable names that accurately represent the values they hold. This improves code readability and makes it easier for other developers to understand your code.

Avoiding complex unpacking patterns

While unpacking variables can simplify assignments, it’s crucial to avoid complex unpacking patterns that may make the code harder to understand. Stick to simple and straightforward unpacking statements for better code clarity.

Using tuple assignment for swapping variables

Python allows you to swap the values of two variables using tuple assignment. This technique is concise and eliminates the need for a temporary variable.

Here’s an example of swapping variables using tuple assignment:

{% raw %}>>> x = 1 >>> y = 2 >>> x, y = y, x >>> print(x, y) 2 1{% endraw %}

Balancing simplicity and readability in assignments

When assigning multiple variables, it’s essential to strike a balance between simplicity and readability. Aim for concise code that is easy to understand and maintain.

Practical examples and use cases

Assigning multiple variables is a versatile technique that can be applied to various scenarios in Python programming. Here are some practical examples:

Assigning multiple variables while iterating over a list

When iterating over a list, you can assign each element to a separate variable:

{% raw %}>>> numbers = [1, 2, 3] >>> for a, b, c in numbers: ... print(a, b, c) 1 2 3{% endraw %}

Unpacking variables from function returns

Functions in Python can return multiple values. By assigning these returned values to multiple variables, you can use them further in your code:

{% raw %}>>> def return_values(): ... return 1, 2 ... >>> x, y = return_values() >>> print(x, y) 1 2{% endraw %}

Handling multiple return values from functions

You can also use the unpacking technique to handle multiple return values from functions:

{% raw %}>>> def return_multiple_values(): ... return 1, 2, 3 ... >>> x, *y, z = return_multiple_values() >>> print(x, y, z) 1 [2] 3{% endraw %}

Parallel assignment of multiple variables

Parallel assignment allows you to assign values to multiple variables simultaneously:

{% raw %}>>> x, y = 1, 2 >>> print(x, y) 1 2{% endraw %}

Common mistakes and troubleshooting tips

Assigning multiple variables in Python can sometimes lead to errors or unexpected results. Here are a few common mistakes and troubleshooting tips:

Unpacking error messages and their meanings

If you encounter an unpacking error, Python will raise a ValueError with a corresponding error message. Read the error message carefully to identify the cause of the error and fix it accordingly.

Handling incorrect number of variables to unpack

If you try to unpack a sequence with a different number of variables, Python will raise a ValueError. To handle this, ensure that the number of variables matches the length of the sequence.

Avoiding common pitfalls in unpacking

When unpacking variables, be wary of potential pitfalls such as mismatched variable names, incorrect sequence types, or forgetting to use the proper unpacking syntax. Double-check your code to avoid these mistakes.

Assigning multiple variables is a crucial concept in Python programming. By mastering this technique, you can write more efficient and readable code. Whether you’re unpacking variables from an iterable or simultaneously assigning values, understanding these techniques will enhance your Python programming skills and make your code more concise and maintainable.

So, start applying these techniques in your Python projects and enjoy the benefits they bring!

Related posts:

  • Mastering Struct Unpack in Python – The Ultimate Guide for Efficient Data Extraction
  • Mastering the Art of Python – Unpacking Tuples for Efficient Programming
  • Mastering Python Dictionary Unpacking – A Comprehensive Guide
  • Mastering Raw String in Python – A Comprehensive Guide for Beginners
  • Mastering Python Type Hints – A Comprehensive Guide to Using Tuples in Type Hinting

Python Programming

Department of Computing | Imperial College London

Writing Reusable and Self-explanatory Programs

  • Chapter 1: Introduction
  • [2.1] Swapping the values of two variables
  • [2.2] How to swap variables
  • [2.3] Simultaneous variable assignments in Python
  • [2.4] Augmented assignment operators
  • [2.5] Test your understanding
  • Chapter 3: Custom functions
  • Chapter 4: Refactoring
  • Chapter 5: Advanced function features
  • Chapter 6: Function scope
  • Chapter 7: Style conventions for functions
  • Chapter 8: git branch
  • Chapter 9: Refactoring the robot
  • Chapter 10: Debugging and testing
  • Chapter 11: Summary

Chapter 2: Shortcut assignment statements

Simultaneous variable assignments in python.

face Josiah Wang

You have seen how you can swap variables when you have only the most basic programming features.

There is actually a different, recommended way to swap variables in Python.

In Python, you can actually assign values to multiple variable simultaneously. Of course, whether this is easy to read is a different question!

You can, however, take advantage of this feature, and swap variables the Pythonic way!

This is actually the recommended way to swap variables in Python.

Trey Hunner

I help developers level-up their python skills, multiple assignment and tuple unpacking improve python code readability.

Mar 7 th , 2018 4:30 pm | Comments

Whether I’m teaching new Pythonistas or long-time Python programmers, I frequently find that Python programmers underutilize multiple assignment .

Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code. This feature often seems simple after you’ve learned about it, but it can be tricky to recall multiple assignment when you need it most .

In this article we’ll see what multiple assignment is, we’ll take a look at common uses of multiple assignment, and then we’ll look at a few uses for multiple assignment that are often overlooked.

Note that in this article I will be using f-strings which are a Python 3.6+ feature. If you’re on an older version of Python, you’ll need to mentally translate those to use the string format method.

How multiple assignment works

I’ll be using the words multiple assignment , tuple unpacking , and iterable unpacking interchangeably in this article. They’re all just different words for the same thing.

Python’s multiple assignment looks like this:

x, y = 10, 20

Here we’re setting x to 10 and y to 20 .

What’s happening at a lower level is that we’re creating a tuple of 10, 20 and then looping over that tuple and taking each of the two items we get from looping and assigning them to x and y in order.

This syntax might make that a bit more clear:

(x, y) = (10, 20)

Parenthesis are optional around tuples in Python and they’re also optional in multiple assignment (which uses a tuple-like syntax). All of these are equivalent:

2 3 4 x, y = 10, 20 >>> x, y = (10, 20) >>> (x, y) = 10, 20 >>> (x, y) = (10, 20)

Multiple assignment is often called “tuple unpacking” because it’s frequently used with tuples. But we can use multiple assignment with any iterable, not just tuples. Here we’re using it with a list:

2 3 4 5 x, y = [10, 20] >>> x 10 >>> y 20

And with a string:

2 3 4 5 x, y = 'hi' >>> x 'h' >>> y 'i'

Anything that can be looped over can be “unpacked” with tuple unpacking / multiple assignment.

Here’s another example to demonstrate that multiple assignment works with any number of items and that it works with variables as well as objects we’ve just created:

2 3 4 5 6 7 point = 10, 20, 30 >>> x, y, z = point >>> print(x, y, z) 10 20 30 >>> (x, y, z) = (z, y, x) >>> print(x, y, z) 30 20 10

Note that on that last line we’re actually swapping variable names, which is something multiple assignment allows us to do easily.

Alright, let’s talk about how multiple assignment can be used.

Unpacking in a for loop

You’ll commonly see multiple assignment used in for loops.

Let’s take a dictionary:

person_dictionary = {'name': "Trey", 'company': "Truthful Technology LLC"}

Instead of looping over our dictionary like this:

2 item in person_dictionary.items(): print(f"Key {item[0]} has value {item[1]}")

You’ll often see Python programmers use multiple assignment by writing this:

2 key, value in person_dictionary.items(): print(f"Key {key} has value {value}")

When you write the for X in Y line of a for loop, you’re telling Python that it should do an assignment to X for each iteration of your loop. Just like in an assignment using the = operator, we can use multiple assignment here.

Is essentially the same as this:

2 3 item in person_dictionary.items(): key, value = item print(f"Key {key} has value {value}")

We’re just not doing an unnecessary extra assignment in the first example.

So multiple assignment is great for unpacking dictionary items into key-value pairs, but it’s helpful in many other places too.

It’s great when paired with the built-in enumerate function:

2 i, line in enumerate(my_file): print(f"Line {i}: {line}")

And the zip function:

2 color, ratio in zip(colors, ratios): print(f"It's {ratio*100}% {color}.")
2 (product, price, color) in zip(products, prices, colors): print(f"{product} is {color} and costs ${price:.2f}")

If you’re unfamiliar with enumerate or zip , see my article on looping with indexes in Python .

Newer Pythonistas often see multiple assignment in the context of for loops and sometimes assume it’s tied to loops. Multiple assignment works for any assignment though, not just loop assignments.

An alternative to hard coded indexes

It’s not uncommon to see hard coded indexes (e.g. point[0] , items[1] , vals[-1] ) in code:

(f"The first item is {items[0]} and the last item is {items[-1]}")

When you see Python code that uses hard coded indexes there’s often a way to use multiple assignment to make your code more readable .

Here’s some code that has three hard coded indexes:

2 3 4 reformat_date(mdy_date_string): """Reformat MM/DD/YYYY string into YYYY-MM-DD string.""" date = mdy_date_string.split('/') return f"{date[2]}-{date[0]}-{date[1]}"

We can make this code much more readable by using multiple assignment to assign separate month, day, and year variables:

2 3 4 reformat_date(mdy_date_string): """Reformat MM/DD/YYYY string into YYYY-MM-DD string.""" month, day, year = mdy_date_string.split('/') return f"{year}-{month}-{day}"

Whenever you see hard coded indexes in your code, stop to consider whether you could use multiple assignment to make your code more readable.

Multiple assignment is very strict

Multiple assignment is actually fairly strict when it comes to unpacking the iterable we give to it.

If we try to unpack a larger iterable into a smaller number of variables, we’ll get an error:

2 3 4 x, y = (10, 20, 30) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 2)

If we try to unpack a smaller iterable into a larger number of variables, we’ll also get an error:

2 3 4 x, y, z = (10, 20) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: not enough values to unpack (expected 3, got 2)

This strictness is pretty great. If we’re working with an item that has a different size than we expected, the multiple assignment will fail loudly and we’ll hopefully now know about a bug in our program that we weren’t yet aware of.

Let’s look at an example. Imagine that we have a short command line program that parses command-line arguments in a rudimentary way, like this:

2 3 4 5 sys new_file = sys.argv[1] old_file = sys.argv[2] print(f"Copying {new_file} to {old_file}")

Our program is supposed to accept 2 arguments, like this:

2 my_program.py file1.txt file2.txt Copying file1.txt to file2.txt

But if someone called our program with three arguments, they will not see an error:

2 my_program.py file1.txt file2.txt file3.txt Copying file1.txt to file2.txt

There’s no error because we’re not validating that we’ve received exactly 2 arguments.

If we use multiple assignment instead of hard coded indexes, the assignment will verify that we receive exactly the expected number of arguments:

2 3 4 sys _, new_file, old_file = sys.argv print(f"Copying {new_file} to {old_file}")

Note : we’re using the variable name _ to note that we don’t care about sys.argv[0] (the name of our program). Using _ for variables you don’t care about is just a convention.

An alternative to slicing

So multiple assignment can be used for avoiding hard coded indexes and it can be used to ensure we’re strict about the size of the tuples/iterables we’re working with.

Multiple assignment can be used to replace hard coded slices too!

Slicing is a handy way to grab a specific portion of the items in lists and other sequences.

Here are some slices that are “hard coded” in that they only use numeric indexes:

2 3 = items[1:] all_but_last_two = items[:-2] items_with_ends_removed = items[1:-1]

Whenever you see slices that don’t use any variables in their slice indexes, you can often use multiple assignment instead. To do this we have to talk about a feature that I haven’t mentioned yet: the * operator.

In Python 3.0, the * operator was added to the multiple assignment syntax, allowing us to capture remaining items after an unpacking into a list:

2 3 4 5 6 numbers = [1, 2, 3, 4, 5, 6] >>> first, *rest = numbers >>> rest [2, 3, 4, 5, 6] >>> first 1

The * operator allows us to replace hard coded slices near the ends of sequences.

These two lines are equivalent:

2 beginning, last = numbers[:-1], numbers[-1] >>> *beginning, last = numbers

These two lines are equivalent also:

2 head, middle, tail = numbers[0], numbers[1:-1], numbers[-1] >>> head, *middle, tail = numbers

With the * operator and multiple assignment you can replace things like this:

(sys.argv[0], sys.argv[1:])

With more descriptive code, like this:

2 , *arguments = sys.argv main(program_name, arguments)

So if you see hard coded slice indexes in your code, consider whether you could use multiple assignment to clarify what those slices really represent.

Deep unpacking

This next feature is something that long-time Python programmers often overlook. It doesn’t come up quite as often as the other uses for multiple assignment that I’ve discussed, but it can be very handy to know about when you do need it.

We’ve seen multiple assignment for unpacking tuples and other iterables. We haven’t yet seen that this is can be done deeply .

I’d say that the following multiple assignment is shallow because it unpacks one level deep:

2 3 4 5 color, point = ("red", (1, 2, 3)) >>> color 'red' >>> point (1, 2, 3)

And I’d say that this multiple assignment is deep because it unpacks the previous point tuple further into x , y , and z variables:

2 3 4 5 6 7 color, (x, y, z) = ("red", (1, 2, 3)) >>> color 'red' >>> x 1 >>> y 2

If it seems confusing what’s going on above, maybe using parenthesis consistently on both sides of this assignment will help clarify things:

(color, (x, y, z)) = ("red", (1, 2, 3))

We’re unpacking one level deep to get two objects, but then we take the second object and unpack it also to get 3 more objects. Then we assign our first object and our thrice-unpacked second object to our new variables ( color , x , y , and z ).

Take these two lists:

2 = [(1, 2), (3, 4), (5, 6)] end_points = [(-1, -2), (-3, 4), (-6, -5)]

Here’s an example of code that works with these lists by using shallow unpacking:

2 3 start, end in zip(start_points, end_points): if start[0] == -end[0] and start[1] == -end[1]: print(f"Point {start[0]},{start[1]} was negated.")

And here’s the same thing with deeper unpacking:

2 3 (x1, y1), (x2, y2) in zip(start_points, end_points): if x1 == -x2 and y1 == -y2: print(f"Point {x1},{y1} was negated.")

Note that in this second case, it’s much more clear what type of objects we’re working with. The deep unpacking makes it apparent that we’re receiving two 2-itemed tuples each time we loop.

Deep unpacking often comes up when nesting looping utilities that each provide multiple items. For example, you may see deep multiple assignments when using enumerate and zip together:

2 3 4 = [1, 2, 3, 4, 2, 1] for i, (first, last) in enumerate(zip(items, reversed(items))): if first != last: raise ValueError(f"Item {i} doesn't match: {first} != {last}")

I said before that multiple assignment is strict about the size of our iterables as we unpack them. With deep unpacking we can also be strict about the shape of our iterables .

This works:

2 3 points = ((1, 2), (-1, -2)) >>> points[0][0] == -points[1][0] and points[0][1] == -points[1][1] True

But this buggy code works too:

2 3 points = ((1, 2, 4), (-1, -2, 3), (6, 4, 5)) >>> points[0][0] == -points[1][0] and points[0][1] == -points[1][1] True

Whereas this works:

2 3 4 points = ((1, 2), (-1, -2)) >>> (x1, y1), (x2, y2) = points >>> x1 == -x2 and y1 == -y2 True

But this does not:

2 3 4 5 points = ((1, 2, 4), (-1, -2, 3), (6, 4, 5)) >>> (x1, y1), (x2, y2) = points Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 2)

With multiple assignment we’re assigning variables while also making particular assertions about the size and shape of our iterables. Multiple assignment will help you clarify your code to both humans (for better code readability ) and to computers (for improved code correctness ).

Using a list-like syntax

I noted before that multiple assignment uses a tuple-like syntax, but it works on any iterable. That tuple-like syntax is the reason it’s commonly called “tuple unpacking” even though it might be more clear to say “iterable unpacking”.

I didn’t mention before that multiple assignment also works with a list-like syntax .

Here’s a multiple assignment with a list-like syntax:

2 3 [x, y, z] = 1, 2, 3 >>> x 1

This might seem really strange. What’s the point of allowing both list-like and tuple-like syntaxes?

I use this feature rarely, but I find it helpful for code clarity in specific circumstances.

Let’s say I have code that used to look like this:

2 most_common(items): return Counter(items).most_common(1)[0][0]

And our well-intentioned coworker has decided to use deep multiple assignment to refactor our code to this:

2 3 most_common(items): (value, times_seen), = Counter(items).most_common(1) return value

See that trailing comma on the left-hand side of the assignment? It’s easy to miss and it makes this code look sort of weird. What is that comma even doing in this code?

That trailing comma is there to make a single item tuple. We’re doing deep unpacking here.

Here’s another way we could write the same code:

2 3 most_common(items): ((value, times_seen),) = Counter(items).most_common(1) return value

This might make that deep unpacking a little more obvious but I’d prefer to see this instead:

2 3 most_common(items): [(value, times_seen)] = Counter(items).most_common(1) return value

The list-syntax in our assignment makes it more clear that we’re unpacking a one-item iterable and then unpacking that single item into value and times_seen variables.

When I see this, I also think I bet we’re unpacking a single-item list . And that is in fact what we’re doing. We’re using a Counter object from the collections module here. The most_common method on Counter objects allows us to limit the length of the list returned to us. We’re limiting the list we’re getting back to just a single item.

When you’re unpacking structures that often hold lots of values (like lists) and structures that often hold a very specific number of values (like tuples) you may decide that your code appears more semantically accurate if you use a list-like syntax when unpacking those list-like structures.

If you’d like you might even decide to adopt a convention of always using a list-like syntax when unpacking list-like structures (frequently the case when using * in multiple assignment):

[first, *rest] = numbers

I don’t usually use this convention myself, mostly because I’m just not in the habit of using it. But if you find it helpful, you might consider using this convention in your own code.

When using multiple assignment in your code, consider when and where a list-like syntax might make your code more descriptive and more clear. This can sometimes improve readability.

Don’t forget about multiple assignment

Multiple assignment can improve both the readability of your code and the correctness of your code. It can make your code more descriptive while also making implicit assertions about the size and shape of the iterables you’re unpacking.

The use for multiple assignment that I often see forgotten is its ability to replace hard coded indexes , including replacing hard coded slices (using the * syntax). It’s also common to overlook the fact that multiple assignment works deeply and can be used with both a tuple-like syntax and a list-like syntax.

It’s tricky to recognize and remember all the cases that multiple assignment can come in handy. Please feel free to use this article as your personal reference guide to multiple assignment.

Get practice with multiple assignment

You don’t learn by reading articles like this one, you learn by writing code .

To get practice writing some readable code using tuple unpacking, sign up for Python Morsels using the form below. If you sign up to Python Morsels using this form, I’ll immediately send you an exercise that involves tuple unpacking.

Intro to Python courses often skip over some fundamental Python concepts .

Sign up below and I'll share ideas new Pythonistas often overlook .

You're nearly signed up. You just need to check your email and click the link there to set your password .

Right after you've set your password you'll receive your first Python Morsels exercise.

Multiple Assignment Syntax in Python

  • python-tricks

The multiple assignment syntax, often referred to as tuple unpacking or extended unpacking, is a powerful feature in Python. There are several ways to assign multiple values to variables at once.

Let's start with a first example that uses extended unpacking . This syntax is used to assign values from an iterable (in this case, a string) to multiple variables:

a : This variable will be assigned the first element of the iterable, which is 'D' in the case of the string 'Devlabs'.

*b : The asterisk (*) before b is used to collect the remaining elements of the iterable (the middle characters in the string 'Devlabs') into a list: ['e', 'v', 'l', 'a', 'b']

c : This variable will be assigned the last element of the iterable: 's'.

The multiple assignment syntax can also be used for numerous other tasks:

Swapping Values

This swaps the values of variables a and b without needing a temporary variable.

Splitting a List

first will be 1, and rest will be a list containing [2, 3, 4, 5] .

Assigning Multiple Values from a Function

This assigns the values returned by get_values() to x, y, and z.

Ignoring Values

Here, you're ignoring the first value with an underscore _ and assigning "Hello" to the important_value . In Python, the underscore is commonly used as a convention to indicate that a variable is being intentionally ignored or is a placeholder for a value that you don't intend to use.

Unpacking Nested Structures

This unpacks a nested structure (Tuple in this example) into separate variables. We can use similar syntax also for Dictionaries:

In this case, we first extract the 'person' dictionary from data, and then we use multiple assignment to further extract values from the nested dictionaries, making the code more concise.

Extended Unpacking with Slicing

first will be 1, middle will be a list containing [2, 3, 4], and last will be 5.

Split a String into a List

*split, is used for iterable unpacking. The asterisk (*) collects the remaining elements into a list variable named split . In this case, it collects all the characters from the string.

The comma , after *split is used to indicate that it's a single-element tuple assignment. It's a syntax requirement to ensure that split becomes a list containing the characters.

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python assignment operators.

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Nahid Hasan

  • Photography Gallery

Tuesday, January 28, 2020

Today's python learning: cascaded assignments, simultaneous assignment, multiline statement, multiline strings, split() method and eval method.

python simultaneous assignment

Mango Habanero Casino Coupons - JTM Hub With the latest 안양 출장샵 Mango Habanero 영주 출장샵 Coupons, shoppers can save on your next purchase with the 공주 출장안마 code "Mango Habanero". 청주 출장마사지 Get 30% off all casino promo 하남 출장샵 code

  • Python »
  • 3.9.19 Documentation »
  • The Python Standard Library »
  • Concurrent Execution »

concurrent.futures — Launching parallel tasks ¶

New in version 3.2.

Source code: Lib/concurrent/futures/thread.py and Lib/concurrent/futures/process.py

The concurrent.futures module provides a high-level interface for asynchronously executing callables.

The asynchronous execution can be performed with threads, using ThreadPoolExecutor , or separate processes, using ProcessPoolExecutor . Both implement the same interface, which is defined by the abstract Executor class.

Executor Objects ¶

An abstract class that provides methods to execute calls asynchronously. It should not be used directly, but through its concrete subclasses.

submit ( fn , / , *args , **kwargs ) ¶ Schedules the callable, fn , to be executed as fn(*args, **kwargs) and returns a Future object representing the execution of the callable. with ThreadPoolExecutor ( max_workers = 1 ) as executor : future = executor . submit ( pow , 323 , 1235 ) print ( future . result ()) map ( func , *iterables , timeout=None , chunksize=1 ) ¶ Similar to map(func, *iterables) except: the iterables are collected immediately rather than lazily; func is executed asynchronously and several calls to func may be made concurrently. The returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to Executor.map() . timeout can be an int or a float. If timeout is not specified or None , there is no limit to the wait time. If a func call raises an exception, then that exception will be raised when its value is retrieved from the iterator. When using ProcessPoolExecutor , this method chops iterables into a number of chunks which it submits to the pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer. For very long iterables, using a large value for chunksize can significantly improve performance compared to the default size of 1. With ThreadPoolExecutor , chunksize has no effect. Changed in version 3.5: Added the chunksize argument. shutdown ( wait=True , * , cancel_futures=False ) ¶ Signal the executor that it should free any resources that it is using when the currently pending futures are done executing. Calls to Executor.submit() and Executor.map() made after shutdown will raise RuntimeError . If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait , the entire Python program will not exit until all pending futures are done executing. If cancel_futures is True , this method will cancel all pending futures that the executor has not started running. Any futures that are completed or running won’t be cancelled, regardless of the value of cancel_futures . If both cancel_futures and wait are True , all futures that the executor has started running will be completed prior to this method returning. The remaining futures are cancelled. You can avoid having to call this method explicitly if you use the with statement, which will shutdown the Executor (waiting as if Executor.shutdown() were called with wait set to True ): import shutil with ThreadPoolExecutor ( max_workers = 4 ) as e : e . submit ( shutil . copy , 'src1.txt' , 'dest1.txt' ) e . submit ( shutil . copy , 'src2.txt' , 'dest2.txt' ) e . submit ( shutil . copy , 'src3.txt' , 'dest3.txt' ) e . submit ( shutil . copy , 'src4.txt' , 'dest4.txt' ) Changed in version 3.9: Added cancel_futures .

ThreadPoolExecutor ¶

ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.

Deadlocks can occur when the callable associated with a Future waits on the results of another Future . For example:

An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.

initializer is an optional callable that is called at the start of each worker thread; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenThreadPool , as well as any attempt to submit more jobs to the pool.

Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5 , assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor .

New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.

Changed in version 3.7: Added the initializer and initargs arguments.

Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4) . This default value preserves at least 5 workers for I/O bound tasks. It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on many-core machines.

ThreadPoolExecutor now reuses idle worker threads before starting max_workers worker threads too.

ThreadPoolExecutor Example ¶

Processpoolexecutor ¶.

The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.

The __main__ module must be importable by worker subprocesses. This means that ProcessPoolExecutor will not work in the interactive interpreter.

Calling Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock.

An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is less than or equal to 0 , then a ValueError will be raised. On Windows, max_workers must be less than or equal to 61 . If it is not then ValueError will be raised. If max_workers is None , then the default chosen will be at most 61 , even if more processors are available. mp_context can be a multiprocessing context or None. It will be used to launch the workers. If mp_context is None or not given, the default multiprocessing context is used.

initializer is an optional callable that is called at the start of each worker process; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenProcessPool , as well as any attempt to submit more jobs to the pool.

Changed in version 3.3: When one of the worker processes terminates abruptly, a BrokenProcessPool error is now raised. Previously, behaviour was undefined but operations on the executor or its futures would often freeze or deadlock.

Changed in version 3.7: The mp_context argument was added to allow users to control the start_method for worker processes created by the pool.

Added the initializer and initargs arguments.

ProcessPoolExecutor Example ¶

Future objects ¶.

The Future class encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit() .

Encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit() and should not be created directly except for testing.

cancel ( ) ¶ Attempt to cancel the call. If the call is currently being executed or finished running and cannot be cancelled then the method will return False , otherwise the call will be cancelled and the method will return True . cancelled ( ) ¶ Return True if the call was successfully cancelled. running ( ) ¶ Return True if the call is currently being executed and cannot be cancelled. done ( ) ¶ Return True if the call was successfully cancelled or finished running. result ( timeout=None ) ¶ Return the value returned by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None , there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call raised an exception, this method will raise the same exception. exception ( timeout=None ) ¶ Return the exception raised by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None , there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call completed without raising, None is returned. add_done_callback ( fn ) ¶ Attaches the callable fn to the future. fn will be called, with the future as its only argument, when the future is cancelled or finishes running. Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them. If the callable raises an Exception subclass, it will be logged and ignored. If the callable raises a BaseException subclass, the behavior is undefined. If the future has already completed or been cancelled, fn will be called immediately.

The following Future methods are meant for use in unit tests and Executor implementations.

set_running_or_notify_cancel ( ) ¶ This method should only be called by Executor implementations before executing the work associated with the Future and by unit tests. If the method returns False then the Future was cancelled, i.e. Future.cancel() was called and returned True . Any threads waiting on the Future completing (i.e. through as_completed() or wait() ) will be woken up. If the method returns True then the Future was not cancelled and has been put in the running state, i.e. calls to Future.running() will return True . This method can only be called once and cannot be called after Future.set_result() or Future.set_exception() have been called. set_result ( result ) ¶ Sets the result of the work associated with the Future to result . This method should only be used by Executor implementations and unit tests. Changed in version 3.8: This method raises concurrent.futures.InvalidStateError if the Future is already done. set_exception ( exception ) ¶ Sets the result of the work associated with the Future to the Exception exception . This method should only be used by Executor implementations and unit tests. Changed in version 3.8: This method raises concurrent.futures.InvalidStateError if the Future is already done.

Module Functions ¶

Wait for the Future instances (possibly created by different Executor instances) given by fs to complete. Duplicate futures given to fs are removed and will be returned only once. Returns a named 2-tuple of sets. The first set, named done , contains the futures that completed (finished or cancelled futures) before the wait completed. The second set, named not_done , contains the futures that did not complete (pending or running futures).

timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None , there is no limit to the wait time.

return_when indicates when this function should return. It must be one of the following constants:

Constant

Description

The function will return when any future finishes or is cancelled.

The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to .

The function will return when all futures finish or are cancelled.

Returns an iterator over the Future instances (possibly created by different Executor instances) given by fs that yields futures as they complete (finished or cancelled futures). Any futures given by fs that are duplicated will be returned once. Any futures that completed before as_completed() is called will be yielded first. The returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to as_completed() . timeout can be an int or float. If timeout is not specified or None , there is no limit to the wait time.

The proposal which described this feature for inclusion in the Python standard library.

Exception classes ¶

Raised when a future is cancelled.

Raised when a future operation exceeds the given timeout.

Derived from RuntimeError , this exception class is raised when an executor is broken for some reason, and cannot be used to submit or execute new tasks.

New in version 3.7.

Raised when an operation is performed on a future that is not allowed in the current state.

New in version 3.8.

Derived from BrokenExecutor , this exception class is raised when one of the workers of a ThreadPoolExecutor has failed initializing.

Derived from BrokenExecutor (formerly RuntimeError ), this exception class is raised when one of the workers of a ProcessPoolExecutor has terminated in a non-clean fashion (for example, if it was killed from the outside).

New in version 3.3.

Table of Contents

  • Executor Objects
  • ThreadPoolExecutor Example
  • ProcessPoolExecutor Example
  • Future Objects
  • Module Functions
  • Exception classes

Previous topic

The concurrent package

subprocess — Subprocess management

  • Report a Bug
  • Show Source

Parallelism, Concurrency, and AsyncIO in Python - by example

Share this tutorial.

  • Hacker News

This tutorial looks at how to speed up CPU-bound and IO-bound operations with multiprocessing, threading, and AsyncIO.

Concurrency vs Parallelism

Sync example, threading example, concurrent.futures example, asyncio example, multiprocessing example.

Concurrency and parallelism are similar terms, but they are not the same thing.

Concurrency is the ability to run multiple tasks on the CPU at the same time. Tasks can start, run, and complete in overlapping time periods. In the case of a single CPU, multiple tasks are run with the help of context switching , where the state of a process is stored so that it can be called and executed later.

Parallelism, meanwhile, is the ability to run multiple tasks at the same time across multiple CPU cores.

Though they can increase the speed of your application, concurrency and parallelism should not be used everywhere. The use case depends on whether the task is CPU-bound or IO-bound.

Tasks that are limited by the CPU are CPU-bound. For example, mathematical computations are CPU-bound since computational power increases as the number of computer processors increases. Parallelism is for CPU-bound tasks. In theory, If a task is divided into n-subtasks, each of these n-tasks can run in parallel to effectively reduce the time to 1/n of the original non-parallel task. Concurrency is preferred for IO-bound tasks, as you can do something else while the IO resources are being fetched.

The best example of CPU-bound tasks is in data science. Data scientists deal with huge chunks of data. For data preprocessing, they can split the data into multiple batches and run them in parallel, effectively decreasing the total time to process. Increasing the number of cores results in faster processing.

Web scraping is IO-bound. Because the task has little effect on the CPU since most of the time is spent on reading from and writing to the network. Other common IO-bound tasks include database calls and reading and writing files to disk. Web applications, like Django and Flask, are IO-bound applications.

If you're interested in learning more about the differences between threads, multiprocessing, and async in Python, check out the Speeding Up Python with Concurrency, Parallelism, and asyncio article.

With that, let's take a look at how to speed up the following tasks:

All of the code examples in this tutorial can be found in the parallel-concurrent-examples-python repo.
  • make_request makes an HTTP request to https://httpbin.org/ip X number of times.
  • make_request_async makes the same HTTP request asynchronously with HTTPX .
  • get_prime_numbers calculates the prime numbers, via the Sieve of Eratosthenes method, from two to the provided limit.

We'll be using the following libraries from the standard library to speed up the above tasks:

  • threading for running tasks concurrently
  • multiprocessing for running tasks in parallel
  • concurrent.futures for running tasks concurrently and in parallel from a single interface
  • asyncio for running tasks concurrency with coroutines managed by the Python interpreter
Library Class/Method Processing Type
threading concurrent
concurrent.futures concurrent
asyncio concurrent (via coroutines)
multiprocessing parallel
concurrent.futures parallel

IO-bound Operation

Again, IO-bound tasks spend more time on IO than on the CPU.

Since web scraping is IO bound, we should use threading to speed up the processing as the retrieving of the HTML (IO) is slower than parsing it (CPU).

Scenario: How to speed up a Python-based web scraping and crawling script?

Let's start with a benchmark.

Here, we made 100 HTTP requests using the make_request function. Since requests happen synchronously, each task is executed sequentially.

So, that's roughly 0.16 seconds per request.

Here, the same make_request function is called 100 times. This time the threading library is used to create a thread for each request.

The total time decreases from ~16s to ~1s.

Since we're using separate threads for each request, you might be wondering why the whole thing didn't take ~0.16s to finish. This extra time is the overhead for managing threads. The Global Interpreter Lock (GIL) in Python makes sure that only one thread uses the Python bytecode at a time.

Here we used concurrent.futures.ThreadPoolExecutor to achieve multithreading. After all the futures/promises are created, we used wait to wait for all of them to complete.

concurrent.futures.ThreadPoolExecutor is actually an abstraction around the multithreading library, which makes it easier to use. In the previous example, we assigned each request to a thread and in total 100 threads were used. But ThreadPoolExecutor defaults the number of worker threads to min(32, os.cpu_count() + 4) . ThreadPoolExecutor exists to ease the process of achieving multithreading. If you want more control over multithreading, use the multithreading library instead.

httpx is used here since requests does not support async operations.

Here, we used asyncio to achieve concurrency.

asyncio is faster than the other methods, because threading makes use of OS (Operating System) threads. So the threads are managed by the OS, where thread switching is preempted by the OS. asyncio uses coroutines, which are defined by the Python interpreter. With coroutines, the program decides when to switch tasks in an optimal way. This is handled by the even_loop in asyncio.

CPU-bound Operation

Scenario: How to speed up a simple data processing script?

Again, let's start with a benchmark.

Here, we executed the get_prime_numbers function for numbers from 1000 to 16000.

Here, we used multiprocessing to calculate the prime numbers.

Here, we achieved multiprocessing using concurrent.futures.ProcessPoolExecutor . Once the jobs are added to futures, wait(futures) waits for them to finish.

concurrent.futures.ProcessPoolExecutor is a wrapper around multiprocessing.Pool . It has the same limitations as the ThreadPoolExecutor . If you want more control over multiprocessing, use multiprocessing.Pool . concurrent.futures provides an abstraction over both multiprocessing and threading, making it easy to switch between the two.

It's worth noting that using multiprocessing to execute the make_request function will be much slower than the threading flavor since the processes will be need to wait for the IO. The multiprocessing approach will be faster then the sync approach, though.

Similarly, using concurrency for CPU-bound tasks is not worth the effort when compared to parallelism.

That being said, using concurrency or parallelism to execute your scripts adds complexity. Your code will generally be harder to read, test, and debug, so only use them when absolutely necessary for long-running scripts.

concurrent.futures is where I generally start since-

  • It's easy to switch back and forth between concurrency and parallelism
  • The dependent libraries don't need to support asyncio ( requests vs httpx )
  • It's cleaner and easier to read over the other approaches

Grab the code from the parallel-concurrent-examples-python repo on GitHub.

Test-Driven Development with Django, Django REST Framework, and Docker

In this course, you'll learn how to set up a development environment with Docker in order to build and deploy a RESTful API powered by Python, Django, and Django REST Framework.

Recommended Tutorials

Stay sharp with course updates.

Join our mailing list to be notified about updates and new releases.

Send Us Feedback

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Simultaneous assignment in python 3.3

I am a newbie at python programming.I am referring to a book "Python Programming: An Introduction to Computer Science." Which is oriented to python 2.Since I cannot lay my hands upon a basic book oriented to python 3, I am facing a syntax problem depicted below

The result i got was

I tried to find the solution in some books like dive into python 3 and core python programming, but i think that they are way too high level for me right now.Please help.

  • syntax-error

user247855's user avatar

  • 1 Welcome to SO. Please use the edit link on your question to show your code. Don't post an image. You should copy/paste the code –  Sede Commented Nov 24, 2015 at 7:27

2 Answers 2

"input" returns only one value at the time, so you can't really assign it for two variables. If you expect two values you may want to split string by space or any other convenient separator.

split(var, 1) - make sure you split string only once into two pieces. map(int...) - convert each string piece value into integer.

Volodymyr Burenin's user avatar

The input function returns one str (in Python 3), which won't be automatically split into two variables. You need to do something like:

pzelasko's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python-3.x syntax-error or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Should we burninate the [lib] tag?
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • "All due respect to jazz." - Does this mean the speaker likes it or dislikes it?
  • Why did Geordi have his visor replaced with ocular implants between Generations and First Contact?
  • Did James Madison say or write that the 10 Commandments are critical to the US nation?
  • Old book about a man who finds an abandoned house with a portal to another world
  • Why does Balarama drink wine?
  • Were there engineers in blimp nacelles, and why were they there?
  • Collaborators write their departments for my (undergraduate) affiliation
  • In WordPress, I want to use code to filter out one menu item (page) from displaying when I call wp_nav_menu() function
  • Reconstructing Euro results
  • Cancellation of the Deutschlandticket
  • Do countries at war always treat each other's diplomats as personae non gratae?
  • Would a spaceport on Ceres make sense?
  • what is the difference between prayer (προσευχῇ) and prayer also translated as supplication (δέησις) in Philippians 4:6?
  • In By His Bootstraps (Heinlein) why is Hitler's name Schickelgruber?
  • Less ridiculous way to prove that an Ascii character compares equal with itself in Coq
  • How to make a 3D ripple effect like the one shown?
  • How to model an optimization problem with mutual exclusivity of two variables, without introducing integer variables?
  • Conveying 'odds and ends'
  • Can I tell a MILP solver to prefer solutions with fewer fractions?
  • How can I take apart a bookshelf?
  • QGIS Labeling expression to format a values list in a series of 2 columns of 2 records
  • Stiff differential equation
  • A 90s (maybe) made-for-TV movie (maybe) about a group of trainees on a spaceship. There is some kind of emergency and all experienced officers die
  • Why can't I conserve mass instead of moles and apply ratio in this problem?

python simultaneous assignment

IMAGES

  1. Pythons Simultaneous Assignment

    python simultaneous assignment

  2. CTEC 121: More on Simultaneous Assignment in Python

    python simultaneous assignment

  3. What is Multiple Assignment in Python and How to use it?

    python simultaneous assignment

  4. PPT

    python simultaneous assignment

  5. PPT

    python simultaneous assignment

  6. Python Tutorial 7,8,9,10

    python simultaneous assignment

VIDEO

  1. Assignment

  2. SLAM G 01

  3. CPIT110 Chapter 2 (#19): 2.6 Simultaneous Assignments

  4. Python [pygame] 00 Installing pygame

  5. B_Sheppard_Assignment_1_ASL_Stories.wmv

  6. UNIT 6 FACTORIZATION AND SIMULTANEOUS EQUATION EX 6.1 Q no 3 AND 4 CLASS 8

COMMENTS

  1. Simultaneous assignment semantics in Python

    And now consider the following two versions of a simultaneous assignment over both a and i: Assignment version 1: a[i],i = i,i+1. Assignment version 2: i,a[i] = i+1,i. I would expect these two versions of simultaneous assignments to be semantically equivalent. However, if you check the values of a and i after each one of the simultaneous ...

  2. Multiple assignment and evaluation order in Python

    See also Multiple assignment semantics regarding the effect and purpose of parentheses on the left-hand side of a multiple assignment. See also Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b? for more complex cases, where the order of assignment matters.

  3. Simultaneous Assignment

    This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example. Here sum would get the sum of x and y and diff would get the difference. This form of assignment seems strange ...

  4. Multiple assignment in Python: Assign multiple values or the same value

    None in Python; Create calendar as text, HTML, list in Python; NumPy: Insert elements, rows, and columns into an array with np.insert() Shuffle a list, string, tuple in Python (random.shuffle, sample) Add and update an item in a dictionary in Python; Cartesian product of lists in Python (itertools.product) Remove a substring from a string in Python

  5. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  6. Mastering Python

    In Python, there are two common techniques for assigning multiple variables - unpacking and simultaneous assignment. Using the unpacking technique The unpacking technique involves assigning the values of an iterable object, such as a tuple or a list, to individual variables.

  7. Pythons Simultaneous Assignment

    Looks at the nature of simultaneous assignments in Python while at the same time covering trace tables as a useful mechanism for describing program execution.

  8. Recurrence relations and simultaneous assignment Python

    Recurrence relations and Python. A video by Raymond Hettinger points out that simultaneous assignment makes it much easier to understand code that evaluates a recurrence relation. His examples were in Python, but the same principle applies to any language supporting simultaneous evaluation. The simplest example of simultaneous evaluation is ...

  9. Lesson 5: Writing Reusable and Self-explanatory Programs > Simultaneous

    Chapter 2: Shortcut assignment statements Simultaneous variable assignments in Python. face Josiah Wang. ... There is actually a different, recommended way to swap variables in Python. In Python, you can actually assign values to multiple variable simultaneously. Of course, whether this is easy to read is a different question! ...

  10. Multiple assignment and tuple unpacking improve Python code readability

    Python's multiple assignment looks like this: >>> x, y = 10, 20. Here we're setting x to 10 and y to 20. What's happening at a lower level is that we're creating a tuple of 10, 20 and then looping over that tuple and taking each of the two items we get from looping and assigning them to x and y in order.

  11. Multiple Assignment Syntax in Python

    The multiple assignment syntax, often referred to as tuple unpacking or extended unpacking, is a powerful feature in Python. There are several ways to assign multiple values to variables at once. Let's start with a first example that uses extended unpacking. This syntax is used to assign values from an iterable (in this case, a string) to ...

  12. Simultaneous Assignment in Python

    This video is about simultaneous assignment in Python. It displays how to assign values to multiple variables at once. ------

  13. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

  14. Simultaneous Assignment in Python

    In this tutorial, we'll learn about how to assign values to multiple variables in a single statement.This concept is very handy when it comes to writing comp...

  15. Algorithmic Problem Solving with Python

    2.3 Statements and the Assignment Operator 2.4 Cascaded and Simultaneous Assignment 2.5 Multi-Line Statements and Multi-Line Strings 2.6 Identifiers and Keywords 2.7 Names and Namespaces 2.8 Additional Arithmetic Operators 2.8.1 Exponentiation 2.8.2 Floor Division 2.8.3 Modulo and divmod() 2.8.4 Augmented Assignment 2.9 Chapter Summary

  16. Today's python learning: Cascaded Assignments, Simultaneous assignment

    Simultaneous assignment: We can also do simultaneous assignments in Python which is not commonly available to other languages. To do that we have to use a comma between expressions and an equal (assignment) operator at the right side. The following variable swapping problem is a perfect example of a simultaneous assignment.

  17. concurrent.futures

    The concurrent.futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class.

  18. How to understand this simultaneous assignment evaluation in python 3

    In your assignment with x = 3 and y = 5. x, y = y, (x+y) the right side is evaluated to a tuple (5, 8) first and then assigned to the values on the left side. Therefore y is 8. You could also think of it as. x, y = 3, 5. temp = y, x + y. x, y = temp. To see what really happens internal, you can disassemble your code:

  19. Parallelism, Concurrency, and AsyncIO in Python

    Grab the code from the parallel-concurrent-examples-python repo on GitHub. Python Amal Shaji. Amal is a full-stack developer interested in deep learning for computer vision and autonomous vehicles. He enjoys working with Python, PyTorch, Go, FastAPI, and Docker. He writes to learn and is a professional introvert.

  20. python

    2. Slicing supports a step parameter. a = "Jack and Jill went up the hill". (user1 , user2) = a.split()[0:4:2] #picks 1 and 3 element in the list. but while it's possible to write funky oneliners in Python for sure it's not the best language for that kind of exercise. answered Nov 30, 2011 at 19:16. 6502.

  21. Simultaneous assignment in python 3.3

    Simultaneous assignment in python 3.3. Ask Question Asked 8 years, 7 months ago. Modified 8 years, 7 months ago. Viewed 926 times 0 I am a newbie at python programming.I am referring to a book "Python Programming: An Introduction to Computer Science." Which is oriented to python 2.Since I cannot lay my hands upon a basic book oriented to python ...