Multiple assignment in Python: Assign multiple values or the same value to multiple variables
In Python, the = operator is used to assign values to variables.
You can assign values to multiple variables in one line.
![](http://rss3.fun/777/templates/cheerup/res/banner1.gif)
Assign multiple values to multiple variables
Assign the same value to multiple variables.
You can assign multiple values to multiple variables by separating them with commas , .
You can assign values to more than three variables, and it is also possible to assign values of different data types to those variables.
When only one variable is on the left side, values on the right side are assigned as a tuple to that variable.
If the number of variables on the left does not match the number of values on the right, a ValueError occurs. You can assign the remaining values as a list by prefixing the variable name with * .
For more information on using * and assigning elements of a tuple and list to multiple variables, see the following article.
- Unpack a tuple and list in Python
You can also swap the values of multiple variables in the same way. See the following article for details:
- Swap values in a list or values of variables in Python
You can assign the same value to multiple variables by using = consecutively.
For example, this is useful when initializing multiple variables with the same value.
After assigning the same value, you can assign a different value to one of these variables. As described later, be cautious when assigning mutable objects such as list and dict .
You can apply the same method when assigning the same value to three or more variables.
Be careful when assigning mutable objects such as list and dict .
If you use = consecutively, the same object is assigned to all variables. Therefore, if you change the value of an element or add a new element in one variable, the changes will be reflected in the others as well.
If you want to handle mutable objects separately, you need to assign them individually.
after c = []; d = [] , c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d .) 3. Data model — Python 3.11.3 documentation
You can also use copy() or deepcopy() from the copy module to make shallow and deep copies. See the following article.
- Shallow and deep copy in Python: copy(), deepcopy()
Related Categories
Related articles.
- NumPy: arange() and linspace() to generate evenly spaced values
- Chained comparison (a < x < b) in Python
- pandas: Get first/last n rows of DataFrame with head() and tail()
- pandas: Filter rows/columns by labels with filter()
- Get the filename, directory, extension from a path string in Python
- Sign function in Python (sign/signum/sgn, copysign)
- How to flatten a list of lists in Python
- 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
- pandas: Extract rows that contain specific strings from a DataFrame
Mastering Multiple Variable Assignment in Python
Python's ability to assign multiple variables in a single line is a feature that exemplifies the language's emphasis on readability and efficiency. In this detailed blog post, we'll explore the nuances of assigning multiple variables in Python, a technique that not only simplifies code but also enhances its readability and maintainability.
Introduction to Multiple Variable Assignment
Python allows the assignment of multiple variables simultaneously. This feature is not only a syntactic sugar but a powerful tool that can make your code more Pythonic.
What is Multiple Variable Assignment?
- Simultaneous Assignment : Python enables the initialization of several variables in a single line, thereby reducing the number of lines of code and making it more readable.
- Versatility : This feature can be used with various data types and is particularly useful for unpacking sequences.
Basic Multiple Variable Assignment
The simplest form of multiple variable assignment in Python involves assigning single values to multiple variables in one line.
Syntax and Examples
Parallel Assignment : Assign values to several variables in parallel.
- Clarity and Brevity : This form of assignment is clear and concise.
- Efficiency : Reduces the need for multiple lines when initializing several variables.
Unpacking Sequences into Variables
Python takes multiple variable assignment a step further with unpacking, allowing the assignment of sequences to individual variables.
Unpacking Lists and Tuples
Direct Unpacking : If you have a list or tuple, you can unpack its elements into individual variables.
Unpacking Strings
Character Assignment : You can also unpack strings into variables with each character assigned to one variable.
Using Underscore for Unwanted Values
When unpacking, you may not always need all the values. Python allows the use of the underscore ( _ ) as a placeholder for unwanted values.
Ignoring Unnecessary Values
Discarding Values : Use _ for values you don't intend to use.
Swapping Variables Efficiently
Multiple variable assignment can be used for an elegant and efficient way to swap the values of two variables.
Swapping Variables
No Temporary Variable Needed : Swap values without the need for an additional temporary variable.
Advanced Unpacking Techniques
Python provides even more advanced ways to handle multiple variable assignments, especially useful with longer sequences.
Extended Unpacking
Using Asterisk ( * ): Python 3 introduced a syntax for extended unpacking where you can use * to collect multiple values.
Best Practices and Common Pitfalls
While multiple variable assignment is a powerful feature, it should be used judiciously.
- Readability : Ensure that your use of multiple variable assignments enhances, rather than detracts from, readability.
- Matching Lengths : Be cautious of the sequence length. The number of elements must match the number of variables being assigned.
Multiple variable assignment in Python is a testament to the language’s design philosophy of simplicity and elegance. By understanding and effectively utilizing this feature, you can write more concise, readable, and Pythonic code. Whether unpacking sequences or swapping values, multiple variable assignment is a technique that can significantly improve the efficiency of your Python programming.
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 variables - assign multiple values, many values to multiple variables.
Python allows you to assign values to multiple variables in one line:
Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking .
Unpack a list:
Learn more about unpacking in our Unpack Tuples Chapter.
Video: Python Variable Names
![python variable assignment multiple lines Python Tutorial on YouTube](https://www.w3schools.com/images/yt_logo_rgb_dark.png)
COLOR PICKER
![python variable assignment multiple lines colorpicker](https://www.w3schools.com/images/colorpicker2000.png)
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.
![python variable assignment multiple lines Python's Assignment Operator: Write Robust Assignments](https://files.realpython.com/media/Pythons-Assignment-Statements-How-Do-They-Work_Watermarked.0a994e47f63c.jpg)
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 variable assignment multiple lines Python Tricks Dictionary Merge](https://realpython.com/static/pytrick-dict-merge.4201a0125a5e.png)
About Leodanis Pozo Ramos
![python variable assignment multiple lines Leodanis Pozo Ramos](https://realpython.com/cdn-cgi/image/width=862,height=862,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/Perfil_final1.9f896bc212f6.jpg)
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:
![python variable assignment multiple lines Aldren Santos](https://realpython.com/cdn-cgi/image/width=959,height=959,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/PP.9b8b026f75b8.jpg)
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 Define Multiple Variables in One Line
In this article, you’ll learn about two variants of this problem.
- Assign multiple values to multiple variables
- Assign the same value to multiple variables
Let’s have a quick overview of both in our interactive code shell:
Exercise : Increase the number of variables to 3 and create a new one-liner!
Let’s dive into the two subtopics in more detail!
Assign Multiple Values to Multiple Variables [One-Liner]
You can use Python’s feature of multiple assignments to assign multiple values to multiple variables. Here is the minimal example:
Most coders would consider this more readable and concise than the multi-liner:
Explanation Multiple Assignment
The syntax of multiple assignments works as follows.
- By using a comma-separated sequence of values on the right side of the equation, you create a tuple on the right side.
- Now, you unpack the tuple into the variables declared on the left side of the equation.
Here’s a minimal code example that shows that you can create a tuple without the usual parentheses syntax:
This explains why the multiple assignment operator is not something you need to remember—if you have understood its underlying concept.
The unpacking syntax in Python is important for many other Python features. It works as follows: you extract an iterable of multiple values into an outer structure of multiple variables.
You can also combine it by unpacking, say, three values into two variables:
The asterisk operator placed in front of a variable tells Python to unpack as many values into this variable as possible. Remember, there’s a tuple on the right side of the equation with three values. Python recognizes that the third value will be placed into variable b . The other two values must be placed into variable a to produce a valid assignment.
Note that it’s not required that all the values in your multiple assignment one-liner have the same type:
The first value has type string, the second value has type integer, and the third value has type float.
But be careful, if the number of variables on the left do not match the number of values in the iterable on the right, Python throws a ValueError !
Here’s an example:
Assign the Same Value to Multiple Variables [One-Liner]
You can use multiple = symbols to assign multiple values to multiple variables. Just create a chain of assignments like this:
This also works for more than two variables:
In this example, you assign the same object (a Python list ) to all three variables.
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills . You’ll learn about advanced Python features such as list comprehension , slicing , lambda functions , regular expressions , map and reduce functions, and slice assignments .
You’ll also learn how to:
- Leverage data structures to solve real-world problems , like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array , shape , axis , type , broadcasting , advanced indexing , slicing , sorting , searching , aggregating , and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups , negative lookaheads , escaped characters , whitespaces, character sets (and negative characters sets ), and greedy/nongreedy operators
- Understand a wide range of computer science topics , including anagrams , palindromes , supersets , permutations , factorials , prime numbers , Fibonacci numbers, obfuscation , searching , and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined , and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!
Three Ways to Create Multiline Strings in Python
![python variable assignment multiple lines python variable assignment multiple lines](https://s3.amazonaws.com/s3.stackabuse.com/media/users/91dc45351236146b499e059557c35823.png)
- Introduction
Multiline strings are a useful feature in Python that allow you to create strings that span multiple lines of code. They can be especially helpful when you need to create long or complex strings, such as for formatting text, writing documentation, or storing data.
In this article, we'll explore three different methods for creating multiline strings in Python. First, we'll look at the most common method - using triple quotes. Then, we'll cover a second method that uses escape characters to continue a string onto a new line. Finally, we'll explore a third method that uses the join() method to concatenate a list of strings into a single multiline string.
By the end of this article, you'll have a clear understanding of the different ways you can create multiline strings in Python, as well as the advantages and limitations of each method. This knowledge will help you choose the best method for your specific use case, and make your Python code more readable and efficient. So, let's get started!
- Method 1: Using Triple Quotes
The most common way to create a multiline string in Python is to use triple quotes . Triple quotes are a set of three quotation marks that allow you to create a string that spans multiple lines.
Note: In this use case, there is no difference between single ( ' ) and double ( " ) quotation marks - so, you can use either triple single quotation marks ( ''' ), as well as triple double quotation marks ( """ ).
Let's take a look at an example of using triple double quotes to create a multiline string:
The string starts and ends with three quotation marks , which tells Python that it's a multiline string. The text between the quotes can span as many lines as needed, and any line breaks or white space will be preserved in the resulting string.
One of the main advantages of using triple quotes to create multiline strings is that they are easy to read and maintain. You can see exactly how the string is formatted and organized, without needing to use escape characters or other tricks to continue the string on multiple lines.
However, one limitation of this method is that it can be difficult to use triple quotes within the string itself, since this can cause conflicts with the opening and closing quotes. In such cases, you might need to use another method, such as escape characters or the join() method, to create your multiline string.
Overall, using triple quotes is a straightforward and effective way to create multiline strings in Python.
- Method 2: Using Escape Characters
Another way to create a multiline string in Python is to use escape characters to continue the string on a new line. Escape characters are special characters that start with a backslash ( \ ) and indicate that the next character should be treated in a special way.
Here's an example of using escape characters to create a multiline string:
Here, we effectively use the backslash character ( \ ) in front of the new line character to indicate that the string should continue on the next line. The backslash itself is not included in the resulting string, so the string appears as a single line of text. It is simply there to help you create a long string on multiple lines.
One advantage of using escape characters to create multiline strings is that it allows you to use other special characters within the string, such as quotes or newlines, without causing conflicts with the opening and closing quotes. However, this method can be more difficult to read and maintain than using triple quotes, especially for longer strings that span many lines.
Using escape characters to create a multiline string can be a useful alternative to using triple quotes, especially if you need to use special characters within the string. However, be sure to only use this method when it makes sense and that the resulting string is still easy to read and understand. We want to improve the readability of our code, not worsen it!
- Method 3: Using the join() Method
A third way to create a multiline string in Python is to use the join() method to concatenate a list of strings into a single string. This method can be especially useful if you already have a list of strings that you want to combine into a multiline string.
Let's show how to use the join() method to create a multiline string:
In this example, we first create a list of strings, with each string representing a new line of text. We then use the join() method to concatenate the strings into a single string, with each string separated by a newline character ( \n ). The resulting string is a multiline string that contains all of the lines from the original list.
Using the join() method to create a multiline string is that it can be a more efficient method for joining long strings, since it avoids creating intermediate strings at each step. Additionally, this method can be useful if you already have a list of strings that you want to combine into a multiline string.
Note : You can use any character or string to join the lines together. So while we use a newline character in our example here, you could theoretically use a space or many other options.
However, one limitation of this method is that it requires you to first create a list of strings, which can be more cumbersome than simply typing out the multiline string directly. Additionally, this method may not be as readable or easy to maintain as using triple quotes, especially for longer strings that span many lines.
Overall, using the join() method to create a multiline string can be a useful alternative to using triple quotes or escape characters, especially if you already have a list of strings that you want to combine into a single string.
- Which Method to Choose
Here we've seen three different methods for creating multiline strings in Python: using triple quotes, using escape characters, and using the join() method. Each of these methods has its own advantages and limitations, and the best method to use will depend on the specific use-case.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Let's take a look at a brief comparison of the three methods:
- Pros : Easy to read and maintain, and can include triple quotes within the string
- Cons : Limited if you need to use triple quotes within the string itself
- Pros : Useful for creating multiline strings with special characters
- Cons : More difficult to read and maintain than triple quotes, and can become cumbersome for longer strings
- Pros : Useful if you already have a list of strings that you want to combine into a multiline string, and can be a more efficient method for joining long strings
- Cons : Requires you to first create a list of strings, and may not be as readable as other methods
Overall, the method you choose to create a multiline string in Python will depend on your specific use case and the preferences of you and your team. In general, it's a good idea to choose the method that is easiest to read and maintain, while still meeting your functional requirements.
Creating multiline strings is a common task in Python, and there are a number of ways to achieve it. In this article, we explored three different methods: using triple quotes, using escape characters, and using the join() method.
Each of these methods has its own advantages and limitations, and the best method to use will depend on your specific use case. Overall, the most commonly used method is the triple quotes, but using escape characters or the join() method may be more appropriate, depending on your situation.
We hope this article has been helpful in explaining the different methods for creating multiline strings in Python. Whether you're working on a personal project or a large-scale software application, understanding these methods will help you write efficient and, more importantly, readable code.
You might also like...
- Hidden Features of Python
- Python Docstrings
- Handling Unix Signals in Python
- The Best Machine Learning Libraries in Python
- Guide to Sending HTTP Requests in Python with urllib3
![](http://rss3.fun/777/templates/cheerup/res/banner1.gif)
Improve your dev skills!
Get tutorials, guides, and dev jobs in your inbox.
No spam ever. Unsubscribe at any time. Read our Privacy Policy.
In this article
![python variable assignment multiple lines python variable assignment multiple lines](https://s3.pingbot.dev/images/monitor-overview.png)
Monitor with Ping Bot
Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.
![OpenAI OpenAI](https://s3.pingbot.dev/icons/system/openai.png)
Vendor Alerts with Ping Bot
Get detailed incident alerts about the status of your favorite vendors. Don't learn about downtime from your customers, be the first to know with Ping Bot.
![Supabase Supabase](https://s3.pingbot.dev/icons/system/supabase.png)
© 2013- 2024 Stack Abuse. All rights reserved.
4 Techniques to Create Python Multiline Strings
![python variable assignment multiple lines Python Multiline Strings Thumbnail](https://www.askpython.com/wp-content/uploads/2020/04/Python-Multiline-Strings-Thumbnail-1024x512.png.webp)
A Python multiline string is the most efficient way of presenting multiple string statements in a formatted and optimized manner.
During the program, there may be a need to store long strings, which cannot be done in one line, it makes the code look horrible and not preferable, so the best way to handle this problem is multiline strings.
In this tutorial, we will be focusing on the different techniques that can be used to create Python multiline strings.
Also Read: Strings in Python
Triple quotes to create multiline strings in Python
The triple quotes can be used to display multiline strings in Python.
- If the input contains string statements with too many characters , then triple quotes can serve us with the need to display it in a formatted way.
- Everything that comes under the triple quotes is considered as the string itself.
The above output explains the advantage of the triple quotes as it printed the string in the same order as it is written in the code.
Using backslash (\) for multiline string creation
The escape sequence — backslash ('\') is used to create multiline strings in Python.
- While creating multiline strings using a backslash(\), the user needs to explicitly mention the spaces between the strings.
In the above output, we can see that it does not handle spaces between strings. The user has to mention it at the time of declaration of multiline strings.
The string.join() method to build a Python multiline string
Python string.join() method has turned out to be an efficient technique for creating Python multiline strings.
The string.join() method handles and manipulates all the spaces between the strings and the user does not need to worry about the same.
Here we can see that the string contains space even though we have not specified it, this is why string.join() method is highly recommended to create Python multiline strings.
Python round brackets () to create multiline strings
Python brackets can be used to create multiline strings and concatenate strings.
The only drawback of this technique is that the user needs to explicitly mention the spaces between the multiline strings.
In the above output, we can see that spaces are not present between each string, which is a drawback of this method, so it is not recommended.
- Python multiline strings are strings split into multiple lines to enhance the readability of the code for the users.
- Python brackets, backslash, and triple quotes can be used to create multiline strings but here, the user needs to mention the use of spaces between the strings.
- Python string.join() method is considered a very efficient way to create multiline strings and moreover, the spaces between the strings are implicitly handled by the method.
- Python indentation rules are not applicable to multiline strings.
- All the escape sequences such as newline(\n), and tab-space(\t) are considered as a part of the string if the multiline string is created using triple quotes.
https://stackoverflow.com/questions/10660435/how-do-i-split-the-definition-of-a-long-string-over-multiple-lines
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 variable assignment multiple lines livingwithcode logo](https://livingwithcode.com/wp-content/themes/livingwithcode/img/livingwithcode-logo.png)
- Python Guide
Assign Multiple Variables in Python
By James L.
In this article, we will discuss the following topics:
Assign the same value to multiple variables
- Assign multiple values to multiple variables (Tuple Unpacking)
We can assign the same value to multiple variables in Python by using the assignment operator ( = ) consecutively between the variable names and assigning a single value at the end.
For example:
a = b = c = 200
The above code is equivalent to
In the above example, all three variables a , b , and c are assigned a value of 200 .
If we have assigned the same value to multiple variables in one line, then we must be very careful when modifying or updating any of the variables.
Lots of beginners get this wrong. Keep in mind that everything in Python is an object and some objects in Python are mutable and some are immutable.
Immutable objects are objects whose value cannot be changed or modified after they have been assigned a value.
Mutable objects are objects whose value can be changed or modified even after they have been assigned a value.
For immutable objects like numeric types (int, float, bool, and complex), str, and tuple, if we update the value of any of the variables, it will not affect others.
In the above example, I initially assigned a value of 200 to all three variables a , b , and c . Later I changed the value of variable b to 500 . When I printed all three variables, we can see that only the value of variable b is changed to 500 while the values of variables a and c are still 200 .
Note : In Python, immutable data types and immutable objects are the same. Also, mutable data types and mutable objects are the same. This may not be the case in other programming languages.
For mutable objects like list, dict, and set, if we update the value of any one of the variables. The value of other variables also gets changed.
In the above example, I initially assigned [1, 2, 3, 4] to all three lists a , b , and c . Later I appended a value of 10 to the list b . When I print all three lists to the console, we can see that the value of 10 is not just appended to list b , it is appended to all three lists a , b , and c .
Assigning the same value of mutable data types to multiple variables in a single line may not be a good idea. The whole purpose of having a mutable object in Python is so that we can update the values.
If you are sure that you won’t be updating the values of mutable data types, then you can assign values of mutable data types to multiple variables in a single line. Otherwise, you should assign them separately.
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
c = [1, 2, 3, 4]
The value of immutable objects cannot be changed doesn’t mean the variable assigned with an immutable object cannot be reassigned to a different value. It simply means the value cannot be changed but the same variable can be assigned a new value.
We can see this behavior of an object by printing the id of the object by using the id() function. The id is the memory address of the object. In Python, all objects have a unique id.
The ID of immutable object:
In the above example, I initially assigned a value of 100 to variable a . When I printed the id of variable a to the console, it is 1686573813072 . Later I changed the value of a to 200 . Now when I print the id of variable a , it is 1686573816272 . Since the id of variable a in the beginning and after I changed the value is different, we can conclude that variable a was pointing to a different memory address in the beginning and now it is pointing to a different memory address. It means that the previous object with its value is replaced by the new object with its new value.
Note : The id will be different from my output id for your machine. May even change every time you run the program.
The ID of mutable object:
In the above example, I have assigned [1, 2, 3, 4] to list a . When I printed the id of list a , it is 1767333244416 . Later, I appended a value of 10 to the list a . When I print the id of the list a , it is still 1767333244416 . Since the id of the list a in the beginning and after I appended a value is the same, we can conclude that list a is still pointing to the same memory address. This means that the value of list a is modified.
Assign multiple variables to the multiple values (Tuple Unpacking)
In Python, we can assign multiple values separated by commas to multiple variables separated by commas in one line using the assignment operator ( = ) .
a, b, c = 100, 200, 300
In the above example, variable a is assigned a value of 100 , variable b is assigned a value of 200 , and variable c is assigned a value of 300 respectively.
We have to make sure that the number of variables is equal to the number of values. Otherwise, it will throw an error.
We can also assign values of different data types to multiple variables in one line.
a, b, c = 2.5, 400, "Hello World"
In the above example, variable a is assigned a value of float data type, variable b is assigned a value of integer data type, and c is assigned a value of string data type.
If the number of values is more than the number of variables, we can still assign those values to multiple variables by placing an asterisk (*) before the variable.
Notice the variable with an asterisk (*) is assigned a list.
This method of assigning multiple variables to multiple values is also called tuple unpacking. In the above examples, what we are doing is, we are unpacking the elements of a tuple and assigning them to multiple separate variables.
In Python, we can create tuples with or without parenthesis.
E.g. a = 1, 2, 3 and a = (1, 2, 3) both are the same thing.
Our first example of assigning multiple variables to multiple values can also be written as:
We can also assign tuples to multiple variables directly.
a, b, c = (100, 200, 300)
We can also unpack other iterable objects like lists, sets, and dictionaries.
Related Posts
Latest posts.
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
Provide Multiple Statements on a Single Line in Python
Python is known for its readability and simplicity, allowing developers to express concepts concisely. While it generally encourages clear and straightforward code, there are scenarios where you might want to execute multiple statements on a single line. In this article, we’ll explore the logic, and syntax, and provide different examples of how to achieve this in Python.
What are Multiple Statements on a Single Line?
The key to placing multiple statements on a single line in Python is to use a semicolon (;) to separate each statement. This allows you to execute multiple commands within the same line, enhancing code compactness. However, it’s important to use this feature judiciously, as overly complex code can lead to reduced readability.
Syntax: The basic syntax for placing multiple statements on a single line is as follows:
How To Provide Multiple Statements On A Single Line In Python?
Below, are the methods of How To Provide Multiple Statements On A Single Line In Python .
- Variable Assignment & Print Statement
- Conditional Statements
- Loop with Break Statement
Variable Assignment and Print Statement
In this example, three statements are executed on a single line. First, we assign the value 5 to the variable x , then we assign 10 to the variable y , and finally, we print the sum of x and y .
Multiple Statements On A Single Line Using Conditional Statements
Here, a conditional statement is used to determine eligibility based on the value of the variable age . The result is assigned to the variable message , and it is printed in a single line.
Multiple Statements On A Single Line Using Loop with Break Statement
In this example, a loop iterates through the numbers list, prints each number, and checks if it equals the target . If the target is found, the found variable is set to True , and the loop is terminated with the break statement .
Multiple Statements On A Single Line Using List Comprehension
In this example, a list comprehension is used to generate a list of squares for even numbers in the range from 1 to 5. The result is assigned to the squares variable, and the list is printed on a single line.
While Python emphasizes readability, there are situations where placing multiple statements on a single line can be useful. The semicolon (;) is the key syntax element for achieving this. However, it’s crucial to strike a balance between conciseness and readability to ensure maintainability and understanding of the code
Please Login to comment...
Similar reads.
- Python Programs
- python-basics
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- 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.
Python assigning multiple variables to same value? list behavior
I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.
Is that correct? what should I use for multiple assignment? what is different from this?
![python variable assignment multiple lines wjandrea's user avatar](https://i.sstatic.net/XRndu.png?s=64)
- 4 Do you want a , b , and c, to all point to the same value (in this case a list), or do you want a=0 , b=3 , and c=5 . In that case, you want a,b,c = [0,3,5] or just a,b,c = 0,3,5 . – chepner Commented May 2, 2013 at 22:52
- Related: Are Python variables pointers? Or else, what are they? (which covers "what is different from this?"), How do I clone a list so that it doesn't change unexpectedly after assignment? (which describes a similar problem that's fundamentally the same), and List of lists changes reflected across sublists unexpectedly (which is structurally the most similar to what you're trying to do) – wjandrea Commented Jun 12 at 16:59
14 Answers 14
If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a as a "variable", and start thinking of it as a "name".
a , b , and c aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.
Names don't have any of that. Values do, of course, and you can have lots of names for the same value.
If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog. If you change the first element of a to 1, the first elements of b and c are 1.
If you want to know if two names are naming the same object, use the is operator:
You then ask:
what is different from this?
Here, you're rebinding the name e to the value 4 . That doesn't affect the names d and f in any way.
In your previous version, you were assigning to a[0] , not to a . So, from the point of view of a[0] , you're rebinding a[0] , but from the point of view of a , you're changing it in-place.
You can use the id function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is can't help:
Notice that a[0] has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0] is also now a name for that same new value. That's because a and b are still naming the same object.
Under the covers, a[0]=1 is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1) .) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1) . Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1 .
* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.
- What if we have, a = b = c = 10; and when we try to update the value of b, it does effect any other? although i checked their ids are the same.? – A.J. Commented Aug 11, 2014 at 14:42
- 3 @user570826: 10 is immutable—that means there is no way to update the value, so your question doesn't make sense. You can point b at a different value, but doing so has no effect on a and c , which are still pointing at the original value. The difference that lists make is that they're mutable—e.g., you can append to a list, or lst[0] = 3 , and that will update the value, which will be visible through all names for that value. – abarnert Commented Aug 11, 2014 at 17:43
- 1 "If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog." I don't know who these people are, could you use a different example, maybe something not so culture based? – Bassie-c Commented Mar 5, 2022 at 21:50
- 1 @Bassie-c, this answer is from 2013. Most people coding at that time would have been old enough to know Notorious B.I.G. People to young to know Notorious B.I.G, are young enough to know Google. This means you must have born before the 70's or so. So let's try this: If you give the King of Rock and Roll a hot dog*, Elvis-the-Pelvis and E. A. Presley have a hot dog. * Don't worry, the King is still alive! So no need to worry if he is a zombie if you see him, and you can feed him all you want. – Lu Kas Commented Sep 15, 2022 at 15:05
Cough cough
- 18 IMHO, this actually answers OP first key question of what should I use for multiple assignment, whereas the higher rated and more cerebral answer above doesn't. – Will Croxford Commented Feb 13, 2019 at 11:08
- 9 Or a,b,c = 1,2,3 without brackets works in Python 2 or 3, if u really want that extra cm of readibility. – Will Croxford Commented Sep 18, 2019 at 13:39
In python, everything is an object, also "simple" variables types (int, float, etc..).
When you changes a variable value, you actually changes it's pointer , and if you compares between two variables it's compares their pointers . (To be clear, pointer is the address in physical computer memory where a variable is stored).
As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.
For your example, when you do:
This means that a and b points to the same address in memory that contains the value 5, but when you do:
It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.
But, when you do:
a and b, again, points to the same location but the difference is that if you change the one of the list values:
It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.
- 6 This is highly misleading. Pointers are certainly not visible at the Python level, and at least two of the four major implementations (PyPy and Jython) don't use them even inside the implementation. – abarnert Commented May 2, 2013 at 23:15
- 1 You welcome to read and explore python internals and you'll discover that every variable in python is actually pointer. – Ori Seri Commented May 2, 2013 at 23:21
- 5 No. In one implementation of Python (CPython), every variable is a pointer to a PyObject . That's not true in other implementations like PyPy or Jython. (In fact, it's not even clear how it could be true, because the languages those implementations are written in don't even have pointers.) – abarnert Commented May 2, 2013 at 23:29
- 1 I think the use of "pointer" in a conceptual sense is ok (perhaps with a disclaimer that implementations may vary), esp if the goal is to convey behavior. – Levon Commented Aug 5, 2015 at 14:47
- 1 @StevenWade Besides the fact that you're replying to a 5-year-old comment: Python is defined in an implementation-agnostic way not just to allow things like PyPy and MicroPython (which are not that rarely used, especially not compared to 2013) to exist, but also to make the language clearer. But that's not even the reason the answer is misleading; just replying to the last in a chain of comments (with all of the intermediate comments long deleted) is kind of missing the point. – abarnert Commented Jul 17, 2018 at 18:54
Yes, that's the expected behavior. a , b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list :
Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0] , you're updating one element of the single list that a , b , and c all refer to. In your second, changing e , you're switching e to be a label for a different object ( 4 instead of 3 ).
You can use id(name) to check if two names represent the same object:
Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:
If you assign a new list to a , then its id will change, so it won't affect b and c 's values:
Integers are immutable, so you cannot change the value without creating a new object:
- 1 id isn't necessarily a memory location. As the docs say, this returns the "identity… an integer… which is guaranteed to be unique and constant for this object during its lifetime." CPython happens to use the memory address as the id , but other Python implementations may not. PyPy, for example, doesn't. And saying "two vars point to the same memory location" is misleading to anyone who understands it C-style. "Two names for the same object" is both more accurate and less misleading. – abarnert Commented May 2, 2013 at 23:18
in your first example a = b = c = [1, 2, 3] you are really saying:
If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:
What you need is this:
![python variable assignment multiple lines pydsigner's user avatar](https://i.sstatic.net/7mj1s.png?s=64)
Simply put, in the first case, you are assigning multiple names to a list . Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.
In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.
![python variable assignment multiple lines Vikas's user avatar](https://i.sstatic.net/rcr6f.jpg?s=64)
The code that does what I need could be this:
To assign multiple variables same value I prefer list
Initialize multiple objects:
E.g: basically a = b = 10 means both a and b are pointing to 10 in the memory, you can test by id(a) and id(b) which comes out exactly equal to a is b as True .
is matches the memory location but not its value, however == matches the value.
let's suppose, you want to update the value of a from 10 to 5 , since the memory location was pointing to the same memory location you will experience the value of b will also be pointing to 5 because of the initial declaration.
The conclusion is to use this only if you know the consequences otherwise simply use , separated assignment like a, b = 10, 10 and won't face the above-explained consequences on updating any of the values because of different memory locations.
The behavior is correct. However, all the variables will share the same reference. Please note the behavior below:
So, yes, it is different in the sense that if you assign a, b and c differently on a separate line, changing one will not change the others.
Here are two codes for you to choose one:
![python variable assignment multiple lines My Car's user avatar](https://i.sstatic.net/ddu0p.jpg?s=64)
The reason for observed behavior was already described in other comments, but there was no solution given, which could help to achieve the required result in a "similar way" as it was given in the topic-description. I would give a try:
In my example - changing of a would neither affect b nor c .
![python variable assignment multiple lines Dr.CKYHC's user avatar](https://lh4.googleusercontent.com/-kWEDFCqdPhw/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclFrD9o5RJ9jFimfTGGmEVDPoYmYw/s96-c/photo.jpg?sz=64)
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 list or ask your own question .
- Featured on Meta
- Announcing a change to the data-dump process
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
Hot Network Questions
- Lindbladian superoperator decomposition
- Existence of disjoint expanders in a graph
- Is this 1-line proof of Cayley–Hamilton incomplete?
- How to deal with unmovable files like MFT when trying to shrink a partition?
- What to do about chain rubbing on unusually placed chainstay?
- A story where a self-declared medium speaks with the voice of a dead skeptic and calls her audience idiots for believing in spiritism
- Justify switch after centering switch
- Doesn't our awareness of qualia imply the brain is non-deterministic?
- When I attach a sensitive pdf encrypted by Adobe with a password, and send it through Gmail with password included, does it make any difference?
- Book where the main character is shown a possible future prediction by a computer
- Can a state get away with failing to comply with treaty obligations during wartime?
- Biology of a Planet Sized Lifeform
- What purity of LOX required before it uses in Rocket Engine?
- Is it safer to sarcastically say "This is not a scam" than honestly say "This is a scam"?
- server side triggers - how to prevent a linked server creation?
- What type of outlet has four vertical slots and how can I modernize it?
- Does forgetful functor commute with limits?
- Using Gamma Ray Lasers to Blow Away Interstellar Medium
- Bicolor/double-sided feathers as part of a thermoregulatory apparatus?
- What can a time traveler use to generate an encryption key to encrypt information so it's only decryptable after a given time period
- Which external monitor to choose for MacBook?
- Have the results of any U.S. presidential election other than 2000, 2020 been widely disputed and litigated?
- Can a superhero story work in novel format?
- Are elements above 137 possible?
![](http://rss3.fun/777/templates/cheerup/res/banner1.gif)
COMMENTS
How Python assign multiple variables at one line works? 1. How to assign 2 variables with the same parameters in 1 line. 0. Python Variable Assignment on One line. 0. Python Syntax for Assigning Multiple Variables Across Multiple Lines. 2. How do I add a line-break to a multiple assignment statement? 5.
Here is an example to break a string into multiple lines in a @dataclass for use with QT style sheets. The end of each line needs to be terminate in double quote followed by a slash, except for the last line. Indentation of the start of each line is also critical.
Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator. While declaring variables in this fashion one ...
You can also swap the values of multiple variables in the same way. See the following article for details: Swap values in a list or values of variables in Python; Assign the same value to multiple variables. You can assign the same value to multiple variables by using = consecutively.
Mastering Multiple Variable Assignment in Python. Python's ability to assign multiple variables in a single line is a feature that exemplifies the language's emphasis on readability and efficiency. In this detailed blog post, we'll explore the nuances of assigning multiple variables in Python, a technique that not only simplifies code but also ...
Python Variables - Assign Multiple Values Previous Next Many Values to Multiple Variables. Python allows you to assign values to multiple variables in one line: Example. x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z)
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.
Assign Multiple Values to Multiple Variables [One-Liner] You can use Python's feature of multiple assignments to assign multiple values to multiple variables. Here is the minimal example: a, b = 1, 2 print(a) # 1 print(b) # 2 You can use the same syntax to assign three or more values to three or more variables in a single line of code:
Method 1: Using Triple Quotes. The most common way to create a multiline string in Python is to use triple quotes. Triple quotes are a set of three quotation marks that allow you to create a string that spans multiple lines. Note: In this use case, there is no difference between single ( ') and double ( ") quotation marks - so, you can use ...
Remember that the number of variables should be equal to the number of elements in the list that you are getting elements from. If you do not use the same number of variables, then you are going to get errors. For example, let us assume that we have the following example, where we are assigning one variable to two values:
In this video, we will explore how to assign multiple variables in one line in Python. This technique allows for concise and readable code, especially when you need to initialize multiple variables simultaneously. This tutorial is perfect for students, professionals, or anyone interested in enhancing their Python programming skills.
Multi-line Statement in Python: In Python, the statements are usually written in a single line and the last character of these lines is newline. To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon ";", and continuation character slash "\". we can use any of these according to our ...
Using backslash (\) for multiline string creation. The escape sequence — backslash ('\') is used to create multiline strings in Python. Syntax: variable = "string1"\"string2"\"stringN". While creating multiline strings using a backslash (\), the user needs to explicitly mention the spaces between the strings. Example:
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 ...
How Python assign multiple variables at one line works? 0. Is there a way to assign numbers to several variables in the same line? 0. Python Variable Assignment on One line. 5. Declare multiple variable in a single line in python. 0. Multivariable assignments across multiple lines in Python. 2.
This means in Python you can exchange two variables with one line: a, b = b, a. It evaluates the right side, creates a tuple (b, a), then expands the tuple and assigns to the left side. There's a special rule that if any of the left-hand-side variables "overlap", the assignment goes left-to-right. i = 0. l = [1, 3, 5, 7]
We can assign the same value to multiple variables in Python by using the assignment operator (=) consecutively between the variable names and assigning a single value at the end. For example: a = b = c = 200. The above code is equivalent to. c = 200. b = c. a = b.
It works so far. But there is warning issued by Pycharm. The warning is 'PEP 8: multiple statement in one line (semicolon)'. I read somewhere PEP 8 is python style guide. PEP8 is a styling guide, offering guidance for best-practices in formatting Python code. The semi-colons are technically valid and your code will run.
A sequence of characters is called a string. In Python, a string is a derived immutable data type—once defined, it cannot be altered. To change the strings, we can utilize Python functions like split, join, and replace. Python has multiple methods for defining strings. Single quotations ("), double quotes (" "), and triple quotes ...
Variable Assignment & Print Statement; Conditional Statements; Loop with Break Statement; Variable Assignment and Print Statement. In this example, three statements are executed on a single line. First, we assign the value 5 to the variable x, then we assign 10 to the variable y, and finally, we print the sum of x and y. Python
If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a as a "variable", and start thinking of it as a "name".. a, b, and c aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.