• Python »
  • 3.12.2 Documentation »
  • The Python Language Reference »
  • 7. Simple statements
  • Theme Auto Light Dark |

7. Simple statements ¶

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:

7.1. Expression statements ¶

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None ). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None , it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None , so that procedure calls do not cause any output.)

7.2. Assignment statements ¶

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

(See section Primaries for the syntax definitions for attributeref , subscription , and slicing .)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy ).

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

If the target is an identifier (name):

If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.

Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal , respectively.

The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError ).

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:

This description does not necessarily apply to descriptor attributes, such as properties created with property() .

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/value pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

For user-defined objects, the __setitem__() method is called with appropriate arguments.

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2] :

The specification for the *target feature.

7.2.1. Augmented assignment statements ¶

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:

(See section Primaries for the syntax definitions of the last three symbols.)

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place , meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] .

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.

7.2.2. Annotated assignment statements ¶

Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement:

The difference from normal Assignment statements is that only a single target is allowed.

For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored.

If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes.

If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last __setitem__() or __setattr__() call.

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.

Changed in version 3.8: Now annotated assignments allow the same expressions in the right hand side as regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error.

7.3. The assert statement ¶

Assert statements are a convenient way to insert debugging assertions into a program:

The simple form, assert expression , is equivalent to

The extended form, assert expression1, expression2 , is equivalent to

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O ). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

7.4. The pass statement ¶

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

7.5. The del statement ¶

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.

Deletion of a target list recursively deletes each target, from left to right.

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.

7.6. The return statement ¶

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None ) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

7.7. The yield statement ¶

A yield statement is semantically equivalent to a yield expression . The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

are equivalent to the yield expression statements

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

For full details of yield semantics, refer to the Yield expressions section.

7.8. The raise statement ¶

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception . If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.

Otherwise, raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException . If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

The type of the exception is the exception instance’s class, the value is the instance itself.

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute. You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. If the raised exception is not handled, both exceptions will be printed:

A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an except or finally clause, or a with statement, is used. The previous exception is then attached as the new exception’s __context__ attribute:

Exception chaining can be explicitly suppressed by specifying None in the from clause:

Additional information on exceptions can be found in section Exceptions , and information about handling exceptions is in section The try statement .

Changed in version 3.3: None is now permitted as Y in raise X from Y .

Added the __suppress_context__ attribute to suppress automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is modified in an except clause, a subsequent raise statement re-raises the exception with the modified traceback. Previously, the exception was re-raised with the traceback it had when it was caught.

7.9. The break statement ¶

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break , the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

7.10. The continue statement ¶

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

7.11. The import statement ¶

The basic import statement (no from clause) is executed in two steps:

find a module, loading and initializing it if necessary

define a name or names in the local namespace for the scope where the import statement occurs.

When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements.

The details of the first step, finding and loading modules, are described in greater detail in the section on the import system , which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code.

If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:

If the module name is followed by as , then the name following as is bound directly to the imported module.

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly

The from form uses a slightly more complex process:

find the module specified in the from clause, loading and initializing it if necessary;

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

if not, attempt to import a submodule with that name and then check the imported module again for that attribute

if the attribute is not found, ImportError is raised.

otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

If the list of identifiers is replaced by a star ( '*' ), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__ ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ( '_' ). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError .

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod . If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod . The specification for relative imports is contained in the Package Relative Imports section.

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.

Raises an auditing event import with arguments module , filename , sys.path , sys.meta_path , sys.path_hooks .

7.11.1. Future statements ¶

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.

The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

the module docstring (if any),

blank lines, and

other future statements.

The only feature that requires using the future statement is annotations (see PEP 563 ).

All historical features enabled by the future statement are still recognized by Python 3. The list includes absolute_import , division , generators , generator_stop , unicode_literals , print_function , nested_scopes and with_statement . They are all redundant because they are always enabled, and only kept for backwards compatibility.

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it.

The direct runtime semantics are the same as for any import statement: there is a standard module __future__ , described later, and it will be imported in the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the future statement.

Note that there is nothing special about the statement:

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions.

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to compile() — see the documentation of that function for details.

A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

The original proposal for the __future__ mechanism.

7.12. The global statement ¶

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global , although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.

Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions.

7.13. The nonlocal statement ¶

When the definition of a function or class is nested (enclosed) within the definitions of other functions, its nonlocal scopes are the local scopes of the enclosing functions. The nonlocal statement causes the listed identifiers to refer to names previously bound in nonlocal scopes. It allows encapsulated code to rebind such nonlocal identifiers. If a name is bound in more than one nonlocal scope, the nearest binding is used. If a name is not bound in any nonlocal scope, or if there is no nonlocal scope, a SyntaxError is raised.

The nonlocal statement applies to the entire scope of a function or class body. A SyntaxError is raised if a variable is used or assigned to prior to its nonlocal declaration in the scope.

The specification for the nonlocal statement.

Programmer’s note: nonlocal is a directive to the parser and applies only to code parsed along with it. See the note for the global statement.

7.14. The type statement ¶

The type statement declares a type alias, which is an instance of typing.TypeAliasType .

For example, the following statement creates a type alias:

This code is roughly equivalent to:

annotation-def indicates an annotation scope , which behaves mostly like a function, but with several small differences.

The value of the type alias is evaluated in the annotation scope. It is not evaluated when the type alias is created, but only when the value is accessed through the type alias’s __value__ attribute (see Lazy evaluation ). This allows the type alias to refer to names that are not yet defined.

Type aliases may be made generic by adding a type parameter list after the name. See Generic type aliases for more.

type is a soft keyword .

New in version 3.12.

Introduced the type statement and syntax for generic classes and functions.

Table of Contents

  • 7.1. Expression statements
  • 7.2.1. Augmented assignment statements
  • 7.2.2. Annotated assignment statements
  • 7.3. The assert statement
  • 7.4. The pass statement
  • 7.5. The del statement
  • 7.6. The return statement
  • 7.7. The yield statement
  • 7.8. The raise statement
  • 7.9. The break statement
  • 7.10. The continue statement
  • 7.11.1. Future statements
  • 7.12. The global statement
  • 7.13. The nonlocal statement
  • 7.14. The type statement

Previous topic

6. Expressions

8. Compound statements

  • Report a Bug
  • Show Source
  • Contributors

Basic Statements in Python

Table of contents, what is a statement in python, statement set, multi-line statements, simple statements, expression statements, the assert statement, the try statement.

Statements in Python

In Python, statements are instructions or commands that you write to perform specific actions or tasks. They are the building blocks of a Python program.

A statement is a line of code that performs a specific action. It is the smallest unit of code that can be executed by the Python interpreter.

Assignment Statement

In this example, the value 10 is assigned to the variable x using the assignment statement.

Conditional Statement

In this example, the if-else statement is used to check the value of x and print a corresponding message.

By using statements, programmers can instruct the computer to perform a variety of tasks, from simple arithmetic operations to complex decision-making processes. Proper use of statements is crucial to writing efficient and effective Python code.

Here's a table summarizing various types of statements in Python:

Please note that this table provides a brief overview of each statement type, and there may be additional details and variations for each statement.

Multi-line statements are a convenient way to write long code in Python without making it cluttered. They allow you to write several lines of code as a single statement, making it easier for developers to read and understand the code. Here are two examples of multi-line statements in Python:

  • Using backslash:
  • Using parentheses:

Simple statements are the smallest unit of execution in Python programming language and they do not contain any logical or conditional expressions. They are usually composed of a single line of code and can perform basic operations such as assigning values to variables , printing out values, or calling functions .

Examples of simple statements in Python:

Simple statements are essential to programming in Python and are often used in combination with more complex statements to create robust programs and applications.

Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result.

In this example, we assign the value 5 to the variable x , then add 3 to x and assign the result ( 8 ) to the variable y . Finally, we print the value of y .

In this example, we define a function square that takes one argument ( x ) and returns its square. We then call the function with the argument 5 and assign the result ( 25 ) to the variable result . Finally, we print the value of result .

Overall, expression statements are an essential part of Python programming and allow for the execution of mathematical and computational operations.

The assert statement in Python is used to test conditions and trigger an error if the condition is not met. It is often used for debugging and testing purposes.

Where condition is the expression that is tested, and message is the optional error message that is displayed when the condition is not met.

In this example, the assert statement tests whether x is equal to 5 . If the condition is met, the statement has no effect. If the condition is not met, an error will be raised with the message x should be 5 .

In this example, the assert statement tests whether y is not equal to 0 before performing the division. If the condition is met, the division proceeds as normal. If the condition is not met, an error will be raised with the message Cannot divide by zero .

Overall, assert statements are a useful tool in Python for debugging and testing, as they can help catch errors early on. They are also easily disabled in production code to avoid any unnecessary overhead.

The try statement in Python is used to catch exceptions that may occur during the execution of a block of code. It ensures that even when an error occurs, the code does not stop running.

Examples of Error Processing

Dive deep into the topic.

  • Match Statements
  • Operators in Python Statements
  • The IF Statement

Contribute with us!

Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.

Profile picture for user AliaksandrSumich

Python One Line Conditional Assignment

Problem : How to perform one-line if conditional assignments in Python?

Example : Say, you start with the following code.

You want to set the value of x to 42 if boo is True , and do nothing otherwise.

Let’s dive into the different ways to accomplish this in Python. We start with an overview:

Exercise : Run the code. Are all outputs the same?

Next, you’ll dive into each of those methods and boost your one-liner superpower !

Method 1: Ternary Operator

The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True . Otherwise, if the expression c evaluates to False , the ternary operator returns the alternative expression y .

Let’s go back to our example problem! You want to set the value of x to 42 if boo is True , and do nothing otherwise. Here’s how to do this in a single line:

While using the ternary operator works, you may wonder whether it’s possible to avoid the ...else x part for clarity of the code? In the next method, you’ll learn how!

If you need to improve your understanding of the ternary operator, watch the following video:

The Python Ternary Operator -- And a Surprising One-Liner Hack

You can also read the related article:

  • Python One Line Ternary

Method 2: Single-Line If Statement

Like in the previous method, you want to set the value of x to 42 if boo is True , and do nothing otherwise. But you don’t want to have a redundant else branch. How to do this in Python?

The solution to skip the else part of the ternary operator is surprisingly simple— use a standard if statement without else branch and write it into a single line of code :

To learn more about what you can pack into a single line, watch my tutorial video “If-Then-Else in One Line Python” :

If-Then-Else in One Line Python

Method 3: Ternary Tuple Syntax Hack

A shorthand form of the ternary operator is the following tuple syntax .

Syntax : You can use the tuple syntax (x, y)[c] consisting of a tuple (x, y) and a condition c enclosed in a square bracket. Here’s a more intuitive way to represent this tuple syntax.

In fact, the order of the <OnFalse> and <OnTrue> operands is just flipped when compared to the basic ternary operator. First, you have the branch that’s returned if the condition does NOT hold. Second, you run the branch that’s returned if the condition holds.

Clever! The condition boo holds so the return value passed into the x variable is the <OnTrue> branch 42 .

Don’t worry if this confuses you—you’re not alone. You can clarify the tuple syntax once and for all by studying my detailed blog article.

Related Article : Python Ternary — Tuple Syntax Hack

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!!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer , and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Unpacking in Python: Beyond Parallel Assignment

single assignment in python

  • Introduction

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

Historically, Python developers have generically referred to this kind of operation as tuple unpacking . However, since this Python feature has turned out to be quite useful and popular, it's been generalized to all kinds of iterables. Nowadays, a more modern and accurate term would be iterable unpacking .

In this tutorial, we'll learn what iterable unpacking is and how we can take advantage of this Python feature to make our code more readable, maintainable, and pythonic.

Additionally, we'll also cover some practical examples of how to use the iterable unpacking feature in the context of assignments operations, for loops, function definitions, and function calls.

  • Packing and Unpacking in Python

Python allows a tuple (or list ) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the * operator) from an iterable on the right side of the assignment.

For historical reasons, Python developers used to call this tuple unpacking . However, since this feature has been generalized to all kind of iterable, a more accurate term would be iterable unpacking and that's what we'll call it in this tutorial.

Unpacking operations have been quite popular among Python developers because they can make our code more readable, and elegant. Let's take a closer look to unpacking in Python and see how this feature can improve our code.

  • Unpacking Tuples

In Python, we can put a tuple of variables on the left side of an assignment operator ( = ) and a tuple of values on the right side. The values on the right will be automatically assigned to the variables on the left according to their position in the tuple . This is commonly known as tuple unpacking in Python. Check out the following example:

When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .

To create a tuple object, we don't need to use a pair of parentheses () as delimiters. This also works for tuple unpacking, so the following syntaxes are equivalent:

Since all these variations are valid Python syntax, we can use any of them, depending on the situation. Arguably, the last syntax is more commonly used when it comes to unpacking in Python.

When we are unpacking values into variables using tuple unpacking, the number of variables on the left side tuple must exactly match the number of values on the right side tuple . Otherwise, we'll get a ValueError .

For example, in the following code, we use two variables on the left and three values on the right. This will raise a ValueError telling us that there are too many values to unpack:

Note: The only exception to this is when we use the * operator to pack several values in one variable as we'll see later on.

On the other hand, if we use more variables than values, then we'll get a ValueError but this time the message says that there are not enough values to unpack:

If we use a different number of variables and values in a tuple unpacking operation, then we'll get a ValueError . That's because Python needs to unambiguously know what value goes into what variable, so it can do the assignment accordingly.

  • Unpacking Iterables

The tuple unpacking feature got so popular among Python developers that the syntax was extended to work with any iterable object. The only requirement is that the iterable yields exactly one item per variable in the receiving tuple (or list ).

Check out the following examples of how iterable unpacking works in Python:

When it comes to unpacking in Python, we can use any iterable on the right side of the assignment operator. The left side can be filled with a tuple or with a list of variables. Check out the following example in which we use a tuple on the right side of the assignment statement:

It works the same way if we use the range() iterator:

Even though this is a valid Python syntax, it's not commonly used in real code and maybe a little bit confusing for beginner Python developers.

Finally, we can also use set objects in unpacking operations. However, since sets are unordered collection, the order of the assignments can be sort of incoherent and can lead to subtle bugs. Check out the following example:

If we use sets in unpacking operations, then the final order of the assignments can be quite different from what we want and expect. So, it's best to avoid using sets in unpacking operations unless the order of assignment isn't important to our code.

  • Packing With the * Operator

The * operator is known, in this context, as the tuple (or iterable) unpacking operator . It extends the unpacking functionality to allow us to collect or pack multiple values in a single variable. In the following example, we pack a tuple of values into a single variable by using the * operator:

For this code to work, the left side of the assignment must be a tuple (or a list ). That's why we use a trailing comma. This tuple can contain as many variables as we need. However, it can only contain one starred expression .

We can form a stared expression using the unpacking operator, * , along with a valid Python identifier, just like the *a in the above code. The rest of the variables in the left side tuple are called mandatory variables because they must be filled with concrete values, otherwise, we'll get an error. Here's how this works in practice.

Packing the trailing values in b :

Packing the starting values in a :

Packing one value in a because b and c are mandatory:

Packing no values in a ( a defaults to [] ) because b , c , and d are mandatory:

Supplying no value for a mandatory variable ( e ), so an error occurs:

Packing values in a variable with the * operator can be handy when we need to collect the elements of a generator in a single variable without using the list() function. In the following examples, we use the * operator to pack the elements of a generator expression and a range object to a individual variable:

In these examples, the * operator packs the elements in gen , and ran into g and r respectively. With his syntax, we avoid the need of calling list() to create a list of values from a range object, a generator expression, or a generator function.

Notice that we can't use the unpacking operator, * , to pack multiple values into one variable without adding a trailing comma to the variable on the left side of the assignment. So, the following code won't work:

If we try to use the * operator to pack several values into a single variable, then we need to use the singleton tuple syntax. For example, to make the above example works, we just need to add a comma after the variable r , like in *r, = range(10) .

  • Using Packing and Unpacking in Practice

Packing and unpacking operations can be quite useful in practice. They can make your code clear, readable, and pythonic. Let's take a look at some common use-cases of packing and unpacking in Python.

  • Assigning in Parallel

One of the most common use-cases of unpacking in Python is what we can call parallel assignment . Parallel assignment allows you to assign the values in an iterable to a tuple (or list ) of variables in a single and elegant statement.

For example, let's suppose we have a database about the employees in our company and we need to assign each item in the list to a descriptive variable. If we ignore how iterable unpacking works in Python, we can get ourself writing code like this:

Even though this code works, the index handling can be clumsy, hard to type, and confusing. A cleaner, more readable, and pythonic solution can be coded as follows:

Using unpacking in Python, we can solve the problem of the previous example with a single, straightforward, and elegant statement. This tiny change would make our code easier to read and understand for newcomers developers.

  • Swapping Values Between Variables

Another elegant application of unpacking in Python is swapping values between variables without using a temporary or auxiliary variable. For example, let's suppose we need to swap the values of two variables a and b . To do this, we can stick to the traditional solution and use a temporary variable to store the value to be swapped as follows:

This procedure takes three steps and a new temporary variable. If we use unpacking in Python, then we can achieve the same result in a single and concise step:

In statement a, b = b, a , we're reassigning a to b and b to a in one line of code. This is a lot more readable and straightforward. Also, notice that with this technique, there is no need for a new temporary variable.

  • Collecting Multiple Values With *

When we're working with some algorithms, there may be situations in which we need to split the values of an iterable or a sequence in chunks of values for further processing. The following example shows how to uses a list and slicing operations to do so:

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!

Even though this code works as we expect, dealing with indices and slices can be a little bit annoying, difficult to read, and confusing for beginners. It has also the drawback of making the code rigid and difficult to maintain. In this situation, the iterable unpacking operator, * , and its ability to pack several values in a single variable can be a great tool. Check out this refactoring of the above code:

The line first, *body, last = seq makes the magic here. The iterable unpacking operator, * , collects the elements in the middle of seq in body . This makes our code more readable, maintainable, and flexible. You may be thinking, why more flexible? Well, suppose that seq changes its length in the road and you still need to collect the middle elements in body . In this case, since we're using unpacking in Python, no changes are needed for our code to work. Check out this example:

If we were using sequence slicing instead of iterable unpacking in Python, then we would need to update our indices and slices to correctly catch the new values.

The use of the * operator to pack several values in a single variable can be applied in a variety of configurations, provided that Python can unambiguously determine what element (or elements) to assign to each variable. Take a look at the following examples:

We can move the * operator in the tuple (or list ) of variables to collect the values according to our needs. The only condition is that Python can determine to what variable assign each value.

It's important to note that we can't use more than one stared expression in the assignment If we do so, then we'll get a SyntaxError as follows:

If we use two or more * in an assignment expression, then we'll get a SyntaxError telling us that two-starred expression were found. This is that way because Python can't unambiguously determine what value (or values) we want to assign to each variable.

  • Dropping Unneeded Values With *

Another common use-case of the * operator is to use it with a dummy variable name to drop some useless or unneeded values. Check out the following example:

For a more insightful example of this use-case, suppose we're developing a script that needs to determine the Python version we're using. To do this, we can use the sys.version_info attribute . This attribute returns a tuple containing the five components of the version number: major , minor , micro , releaselevel , and serial . But we just need major , minor , and micro for our script to work, so we can drop the rest. Here's an example:

Now, we have three new variables with the information we need. The rest of the information is stored in the dummy variable _ , which can be ignored by our program. This can make clear to newcomer developers that we don't want to (or need to) use the information stored in _ cause this character has no apparent meaning.

Note: By default, the underscore character _ is used by the Python interpreter to store the resulting value of the statements we run in an interactive session. So, in this context, the use of this character to identify dummy variables can be ambiguous.

  • Returning Tuples in Functions

Python functions can return several values separated by commas. Since we can define tuple objects without using parentheses, this kind of operation can be interpreted as returning a tuple of values. If we code a function that returns multiple values, then we can perform iterable packing and unpacking operations with the returned values.

Check out the following example in which we define a function to calculate the square and cube of a given number:

If we define a function that returns comma-separated values, then we can do any packing or unpacking operation on these values.

  • Merging Iterables With the * Operator

Another interesting use-case for the unpacking operator, * , is the ability to merge several iterables into a final sequence. This functionality works for lists, tuples, and sets. Take a look at the following examples:

We can use the iterable unpacking operator, * , when defining sequences to unpack the elements of a subsequence (or iterable) into the final sequence. This will allow us to create sequences on the fly from other existing sequences without calling methods like append() , insert() , and so on.

The last two examples show that this is also a more readable and efficient way to concatenate iterables. Instead of writing list(my_set) + my_list + list(my_tuple) + list(range(1, 4)) + list(my_str) we just write [*my_set, *my_list, *my_tuple, *range(1, 4), *my_str] .

  • Unpacking Dictionaries With the ** Operator

In the context of unpacking in Python, the ** operator is called the dictionary unpacking operator . The use of this operator was extended by PEP 448 . Now, we can use it in function calls, in comprehensions and generator expressions, and in displays .

A basic use-case for the dictionary unpacking operator is to merge multiple dictionaries into one final dictionary with a single expression. Let's see how this works:

If we use the dictionary unpacking operator inside a dictionary display, then we can unpack dictionaries and combine them to create a final dictionary that includes the key-value pairs of the original dictionaries, just like we did in the above code.

An important point to note is that, if the dictionaries we're trying to merge have repeated or common keys, then the values of the right-most dictionary will override the values of the left-most dictionary. Here's an example:

Since the a key is present in both dictionaries, the value that prevail comes from vowels , which is the right-most dictionary. This happens because Python starts adding the key-value pairs from left to right. If, in the process, Python finds keys that already exit, then the interpreter updates that keys with the new value. That's why the value of the a key is lowercased in the above example.

  • Unpacking in For-Loops

We can also use iterable unpacking in the context of for loops. When we run a for loop, the loop assigns one item of its iterable to the target variable in every iteration. If the item to be assigned is an iterable, then we can use a tuple of target variables. The loop will unpack the iterable at hand into the tuple of target variables.

As an example, let's suppose we have a file containing data about the sales of a company as follows:

From this table, we can build a list of two-elements tuples. Each tuple will contain the name of the product, the price, and the sold units. With this information, we want to calculate the income of each product. To do this, we can use a for loop like this:

This code works as expected. However, we're using indices to get access to individual elements of each tuple . This can be difficult to read and to understand by newcomer developers.

Let's take a look at an alternative implementation using unpacking in Python:

We're now using iterable unpacking in our for loop. This makes our code way more readable and maintainable because we're using descriptive names to identify the elements of each tuple . This tiny change will allow a newcomer developer to quickly understand the logic behind the code.

It's also possible to use the * operator in a for loop to pack several items in a single target variable:

In this for loop, we're catching the first element of each sequence in first . Then the * operator catches a list of values in its target variable rest .

Finally, the structure of the target variables must agree with the structure of the iterable. Otherwise, we'll get an error. Take a look at the following example:

In the first loop, the structure of the target variables, (a, b), c , agrees with the structure of the items in the iterable, ((1, 2), 2) . In this case, the loop works as expected. In contrast, the second loop uses a structure of target variables that don't agree with the structure of the items in the iterable, so the loop fails and raises a ValueError .

  • Packing and Unpacking in Functions

We can also use Python's packing and unpacking features when defining and calling functions. This is a quite useful and popular use-case of packing and unpacking in Python.

In this section, we'll cover the basics of how to use packing and unpacking in Python functions either in the function definition or in the function call.

Note: For a more insightful and detailed material on these topics, check out Variable-Length Arguments in Python with *args and **kwargs .

  • Defining Functions With * and **

We can use the * and ** operators in the signature of Python functions. This will allow us to call the function with a variable number of positional arguments ( * ) or with a variable number of keyword arguments, or both. Let's consider the following function:

The above function requires at least one argument called required . It can accept a variable number of positional and keyword arguments as well. In this case, the * operator collects or packs extra positional arguments in a tuple called args and the ** operator collects or packs extra keyword arguments in a dictionary called kwargs . Both, args and kwargs , are optional and automatically default to () and {} respectively.

Even though the names args and kwargs are widely used by the Python community, they're not a requirement for these techniques to work. The syntax just requires * or ** followed by a valid identifier. So, if you can give meaningful names to these arguments, then do it. That will certainly improve your code's readability.

  • Calling Functions With * and **

When calling functions, we can also benefit from the use of the * and ** operator to unpack collections of arguments into separate positional or keyword arguments respectively. This is the inverse of using * and ** in the signature of a function. In the signature, the operators mean collect or pack a variable number of arguments in one identifier. In the call, they mean unpack an iterable into several arguments.

Here's a basic example of how this works:

Here, the * operator unpacks sequences like ["Welcome", "to"] into positional arguments. Similarly, the ** operator unpacks dictionaries into arguments whose names match the keys of the unpacked dictionary.

We can also combine this technique and the one covered in the previous section to write quite flexible functions. Here's an example:

The use of the * and ** operators, when defining and calling Python functions, will give them extra capabilities and make them more flexible and powerful.

Iterable unpacking turns out to be a pretty useful and popular feature in Python. This feature allows us to unpack an iterable into several variables. On the other hand, packing consists of catching several values into one variable using the unpacking operator, * .

In this tutorial, we've learned how to use iterable unpacking in Python to write more readable, maintainable, and pythonic code.

With this knowledge, we are now able to use iterable unpacking in Python to solve common problems like parallel assignment and swapping values between variables. We're also able to use this Python feature in other structures like for loops, function calls, and function definitions.

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

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Leodanis is an industrial engineer who loves Python and software development. He is a self-taught Python programmer with 5+ years of experience building desktop applications with PyQt.

In this article

single assignment in python

Building Your First Convolutional Neural Network With Keras

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup

Data Visualization in Python with Matplotlib and Pandas

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

© 2013- 2024 Stack Abuse. All rights reserved.

How to Write the Python if Statement in one Line

Author's photo

  • online practice

Have you ever heard of writing a Python if statement in a single line? Here, we explore multiple ways to do exactly that, including using conditional expressions in Python.

The if statement is one of the most fundamental statements in Python. In this article, we learn how to write the Python if in one line.

The if is a key piece in writing Python code. It allows developers to control the flow and logic of their code based on information received at runtime. However, many Python developers do not know they may reduce the length and complexity of their if statements by writing them in a single line.

For this article, we assume you’re somewhat familiar with Python conditions and comparisons. If not, don’t worry! Our Python Basics Course will get you up to speed in no time. This course is included in the Python Basics Track , a full-fledged Python learning track designed for complete beginners.

We start with a recap on how Python if statements work. Then, we explore some examples of how to write if statements in a single line. Let’s get started!

How the if Statement Works in Python

Let’s start with the basics. An if statement in Python is used to determine whether a condition is True or False . This information can then be used to perform specific actions in the code, essentially controlling its logic during execution.

The structure of the basic if statement is as follows:

The <expression> is the code that evaluates to either True or False . If this code evaluates to True, then the code below (represented by <perform_action> ) executes.

Python uses whitespaces to indicate which lines are controlled by the if statement. The if statement controls all indented lines below it. Typically, the indentation is set to four spaces (read this post if you’re having trouble with the indentation ).

As a simple example, the code below prints a message if and only if the current weather is sunny:

The if statement in Python has two optional components: the elif statement, which executes only if the preceding if/elif statements are False ; and the else statement, which executes only if all of the preceding if/elif statements are False. While we may have as many elif statements as we want, we may only have a single else statement at the very end of the code block.

Here’s the basic structure:

Here’s how our previous example looks after adding elif and else statements. Change the value of the weather variable to see a different message printed:

How to Write a Python if in one Line

Writing an if statement in Python (along with the optional elif and else statements) uses a lot of whitespaces. Some people may find it confusing or tiresome to follow each statement and its corresponding indented lines.

To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line !

Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here’s the basic structure:

As you can see, not much has changed. We simply need to “pull” the indented line <perform_action> up to the right of the colon character ( : ). It’s that simple!

Let’s check it with a real example. The code below works as it did previously despite the if statement being in a single line. Test it out and see for yourself:

Writing a Python if Statement With Multiple Actions in one Line

That’s all well and good, but what if my if statement has multiple actions under its control? When using the standard indentation, we separate different actions in multiple indented lines as the structure below shows:

Can we do this in a single line? The surprising answer is yes! We use semicolons to separate each action in the same line as if placed in different lines.

Here’s how the structure looks:

And an example of this functionality:

Have you noticed how each call to the print() function appears in its own line? This indicates we have successfully executed multiple actions from a single line. Nice!

By the way, interested in learning more about the print() function? We have an article on the ins and outs of the print() function .

Writing a Full Python if/elif/else Block Using Single Lines

You may have seen this coming, but we can even write elif and else statements each in a single line. To do so, we use the same syntax as writing an if statement in a single line.

Here’s the general structure:

Looks simple, right? Depending on the content of your expressions and actions, you may find this structure easier to read and understand compared to the indented blocks.

Here’s our previous example of a full if/elif/else block, rewritten as single lines:

Using Python Conditional Expressions to Write an if/else Block in one Line

There’s still a final trick to writing a Python if in one line. Conditional expressions in Python (also known as Python ternary operators) can run an if/else block in a single line.

A conditional expression is even more compact! Remember it took at least two lines to write a block containing both if and else statements in our last example.

In contrast, here’s how a conditional expression is structured:

The syntax is somewhat harder to follow at first, but the basic idea is that <expression> is a test. If the test evaluates to True , then <value_if_true> is the result. Otherwise, the expression results in <value_if_false> .

As you can see, conditional expressions always evaluate to a single value in the end. They are not complete replacements for an if/elif/else block. In fact, we cannot have elif statements in them at all. However, they’re most helpful when determining a single value depending on a single condition.

Take a look at the code below, which determines the value of is_baby depending on whether or not the age is below five:

This is the exact use case for a conditional expression! Here’s how we rewrite this if/else block in a single line:

Much simpler!

Go Even Further With Python!

We hope you now know many ways to write a Python if in one line. We’ve reached the end of the article, but don’t stop practicing now!

If you do not know where to go next, read this post on how to get beyond the basics in Python . If you’d rather get technical, we have a post on the best code editors and IDEs for Python . Remember to keep improving!

You may also like

single assignment in python

How Do You Write a SELECT Statement in SQL?

single assignment in python

What Is a Foreign Key in SQL?

single assignment in python

Enumerate and Explain All the Basic Elements of an SQL Query

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.

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

Better Data Science

Python If-Else Statement in One Line - Ternary Operator Explained

Single-line conditionals in python here’s when to and when not to use them.

Python isn’t the fastest programming language out there, but boy is it readable and efficient to write. Everyone knows what conditional statements are, but did you know you can write if statements in one line of Python code? As it turns out you can, and you’ll learn all about it today.

After reading, you’ll know everything about Python’s If Else statements in one line. You’ll understand when to use them, and when it’s best to avoid them and stick to conventional conditional statements.

Don’t feel like reading? Watch my video instead:

Want to get hired as a data scientist? Running a data science blog might help:

Can Blogging About Data Science Really Get You Hired as a Data Scientist?

What’s Wrong With the Normal If Statement?

Absolutely nothing. Splitting conditional statements into multiple lines of code has been a convention for ages. Most programming languages require the usage of curly brackets, and hence the single line if statements are not an option. Other languages allow writing only simple conditionals in a single line.

And then there’s Python. Before diving into If Else statements in one line, let’s first make a short recap on regular conditionals.

For example, you can check if a condition is true with the following syntax:

The variable age is less than 18 in this case, so Go home. is printed to the console. You can spice things up by adding an else condition that gets evaluated if the first condition is False :

This time age is greater than 18, so Welcome! gets printed to the console. Finally, you can add one or multiple elif conditions. These are used to capture the in-between cases. For example, you can print something entirely different if age is between 16 (included) and 18 (excluded):

The variable age is 17, which means the condition under elif is True , hence Not sure... is printed to the console.

Pretty basic stuff, so we naturally don’t want to spend so many lines of code writing it. As it turns out, you can use the ternary operator in Python to evaluate conditions in a single line.

Ternary Operator in Python

A ternary operator exists in some programming languages, and it allows you to shorten a simple If-Else block. It takes in 3 or more operands:

  • Value if true - A value that’s returned if the condition evaluates to True.
  • Condition - A boolean condition that has to be satisfied to return value if true.
  • Value if false - A value that’s returned if the condition evaluates to False. In code, it would look like this:

You can even write else-if logic in Python’s ternary operator. In that case, the syntax changes slightly:

I have to admit - it looks a bit abstract when written like this. You’ll see plenty of practical examples starting from the next section.

One-Line If Statement (Without Else)

A single-line if statement just means you’re deleting the new line and indentation. You’re still writing the same code, with the only twist being that it takes one line instead of two.

Note: One-line if statement is only possible if there’s a single line of code following the condition. In any other case, wrap the code that will be executed inside a function.

Here’s how to transform our two-line if statement to a single-line conditional:

As before, age is less than 18 so Go home. gets printed.

What if you want to print three lines instead of one? As said before, the best practice is to wrap the code inside a function:

One-line if statements in Python are pretty boring. The real time and space saving benefit happens when you add an else condition.

You’ll benefit the most from one-line if statements if you add one or multiple else conditions.

One-Line If-Else Statement

Now we can fully leverage the power of Python’s ternary operator. The code snippet below stores Go home. to a new variable outcome if the age is less than 18 or Welcome! otherwise:

As you would guess, Welcome! is printed to the console as age is set to 19. If you want to print multiple lines or handle more complex logic, wrap everything you want to be executed into a function - just as before.

You now have a clear picture of how the ternary operator works on a simple one-line if-else statement. We can add complexity by adding more conditions to the operator.

One-Line If-Elif-Else Statement

Always be careful when writing multiple conditions in a single line of code. The logic will still work if the line is 500 characters long, but it’s near impossible to read and maintain it.

You should be fine with two conditions in one line, as the code is still easy to read. The following example prints Go home. if age is below 16, Not Sure... if age is between 16 (included) and 18 (excluded), and Welcome otherwise:

You’ll see Not sure... printed to the console, since age is set to 17. What previously took us six lines of code now only takes one. Neat improvement, and the code is still easy to read and maintain.

What else can you do with one-line if statements? Well, a lot. We’ll explore single-line conditionals for list operations next.

Example: One-Line Conditionals for List Operations

Applying some logic to a list involves applying the logic to every list item, and hence iterating over the entire list. Before even thinking about a real-world example, let’s see how you can write a conditional statement for every list item in a single line of code.

How to Write IF and FOR in One Line

You’ll need to make two changes to the ternary operator:

Surround the entire line of code with brackets [] Append the list iteration code (for element in array) after the final else Here’s how the generic syntax looks like:

It’s not that hard, but let’s drive the point home with an example. The following code snippet prints + if the current number of a range is greater than 5 and - otherwise. The numbers range from 1 to 10 (included):

Image 1 - If and For in a single line in Python (image by author)

Image 1 - If and For in a single line in Python (image by author)

Let’s now go over an additional real-world example.

Example: Did Student Pass the Exam?

To start, we’ll declare a list of students. Each student is a Python dictionary object with two keys: name and test score:

We want to print that the student has passed the exam if the score is 50 points or above. If the score was below 50 points, we want to print that the student has failed the exam.

In traditional Python syntax, we would manually iterate over each student in the list and check if the score is greater than 50:

Image 2 - List iteration with traditional Python syntax (image by author)

Image 2 - List iteration with traditional Python syntax (image by author)

The code works, but we need 5 lines to make a simple check and store the results. You can use your newly-acquired knowledge to reduce the amount of code to a single line:

Image 3 - One-line conditional and a loop with Python (image by author)

Image 3 - One-line conditional and a loop with Python (image by author)

The results are identical, but we have a much shorter and neater code. It’s just on the boundary of being unreadable, which is often a tradeoff with ternary operators and single-line loops. You often can’t have both readable code and short Python scripts.

Just because you can write a conditional in one line, it doesn’t mean you should. Readability is a priority. Let’s see in which cases you’re better off with traditional if statements.

Be Careful With One-Line Conditionals

Just because code takes less vertical space doesn’t mean it’s easier to read. Now you’ll see the perfect example of that claim.

The below snippet checks a condition for every possible grade (1-5) with a final else condition capturing invalid input. The conditions take 12 lines of code to write, but the entire snippet is extremely readable:

As expected, you’ll see Grade = 1 printed to the console, but that’s not what we’re interested in. We want to translate the above snippet into a one-line if-else statement with the ternary operator.

It’s possible - but the end result is messy and unreadable:

This is an example of an extreme case where you have multiple conditions you have to evaluate. It’s better to stick with the traditional if statements, even though they take more vertical space.

Take home point: A ternary operator with more than two conditions is just a nightmare to write and debug.

And there you have it - everything you need to know about one-line if-else statements in Python. You’ve learned all there is about the ternary operator, and how to write conditionals starting with a single if to five conditions in between.

Remember to keep your code simple. The code that’s easier to read and maintain is a better-written code at the end of the day. Just because you can cram everything into a single line, doesn’t mean you should. You’ll regret it as soon as you need to make some changes.

An even cleaner way to write long conditionals is by using structural pattern matching - a new feature introduced in Python 3.10. It brings the beloved switch statement to Python for extra readability and speed of development.

What do you guys think of one-line if-else statements in Python? Do you use them regularly or have you switched to structural pattern matching? Let me know in the comment section below.

A Comprehensive Guide to Augmented Assignment Operators in Python

Augmented assignment operators are a vital part of the Python programming language. These operators provide a shortcut for assigning the result of an operation back to a variable in an expressive and efficient manner.

In this comprehensive guide, we will cover the following topics related to augmented assignment operators in Python:

Table of Contents

What are augmented assignment operators, arithmetic augmented assignments, bitwise augmented assignments, sequence augmented assignments, advantages of augmented assignment operators, augmented assignment with mutable types, operator precedence and order of evaluation, updating multiple references, augmented assignment vs normal assignment, comparisons to other languages, best practices and style guide.

Augmented assignment operators are a shorthand technique that combines an arithmetic or bitwise operation with an assignment.

The augmented assignment operator performs the operation on the current value of the variable and assigns the result back to the same variable in a compact syntax.

For example:

Here x += 3 is equivalent to x = x + 3 . The += augmented assignment operator adds the right operand 3 to the current value of x , which is 2 . It then assigns the result 5 back to x .

This shorthand allows you to reduce multiple lines of code into a concise single line expression.

Some key properties of augmented assignment operators in Python:

  • Operators act inplace directly modifying the variable’s value
  • Work on mutable types like lists, sets, dicts unlike normal operators
  • Generally have equivalent compound statement forms using standard operators
  • Have right-associative evaluation order unlike arithmetic operators
  • Available for arithmetic, bitwise, and sequence operations

Now let’s look at the various augmented assignment operators available in Python.

Augmented Assignment Operators List

Python supports augmented versions of all the arithmetic, bitwise, and sequence assignment operators.

These perform the standard arithmetic operations like addition or exponentiation and assign the result back to the variable.

These allow you to perform bitwise AND, OR, XOR, right shift, and left shift operations combined with assignment.

The += operator can also be used to concatenate sequences like lists, tuples, and strings.

These operators provide a shorthand for sequence concatenation.

Some key advantages of using augmented assignment operators:

Conciseness : Performs an operation and assignment in one concise expression rather than multiple lines or steps.

Readability : The operator itself makes the code’s intention very clear. x += 3 is more readable than x = x + 3 .

Efficiency : Saves executing multiple operations and creates less intermediate objects compared to chaining or sequencing the operations. The variable is modified in-place.

For these reasons, augmented assignments should be preferred over explicit expansion into longer compound statements in most cases.

Some examples of effective usage:

  • Incrementing/decrementing variables: index += 1
  • Accumulating sums: total += price
  • Appending to sequences: names += ["Sarah", "John"]
  • Bit masking tasks: bits |= 0b100

So whenever you need to assign the result of some operation back into a variable, consider using the augmented version.

Common Mistakes to Avoid

While augmented assignment operators are very handy, some common mistakes can occur:

Augmented assignments act inplace and modify the existing object. This can be problematic with mutable types like lists:

In contrast, normal operators with immutable types create a new object:

So be careful when using augmented assignments with mutable types, as they modify the object in-place rather than creating a new object.

Augmented assignment operators have right-associativity. This can cause unexpected results:

The right-most operation y += 1 is evaluated first updating y. Then x += y uses the new value of y.

To avoid this, use parenthesis to control order of evaluation:

When you augmented assign to a variable, it updates all references to that object:

y also reflects the change since it points to the same mutable list as x .

To avoid this, reassign the variable rather than using augmented assignment:

While the augmented assignment operators provide a shorthand, they differ from standard assignment in some key ways:

Inplace modification : Augmented assignment acts inplace and modifies the existing variable rather than creating a new object.

Mutable types : Works directly on mutable types like lists, sets, and dicts unlike normal assignment.

Order of evaluation : Has right-associativity unlike left-associativity of normal assignment.

Multiple references : Affects all references to a mutable object unlike normal assignment.

In summary, augmented assignment operators combine both an operation and assignment but evaluate differently than standard operators.

Augmented assignments exist in many other languages like C/C++, Java, JavaScript, Go, Rust, etc. Some key differences to Python:

In C/C++ augmented assignments return the assigned value allowing usage in expressions unlike Python which returns None .

Java and JavaScript don’t allow augmented assignment with strings unlike Python which supports += for concatenation.

Go doesn’t have an increment/decrement operator like ++ and -- . Python’s += 1 and -= 1 serves a similar purpose.

Rust doesn’t allow built-in types like integers to be reassigned with augmented assignment and requires mutable variables be defined with mut .

So while augmented assignment is common across languages, Python provides some unique behaviors to be aware of.

Here are some best practices when using augmented assignments in Python:

Use whitespace around the operators: x += 1 rather than x+=1 for readability.

Limit chaining augmented assignments like x = y = 0 . Use temporary variables if needed for clarity.

Don’t overuse augmented assignment especially with mutable types. Reassignment may be better if the original object shouldn’t be changed.

Watch the order of evaluation with multiple augmented assignments on one line due to right-associativity.

Consider parentheses for explicit order of evaluation: x += (y + z) rather than relying on precedence.

For increments/decrements, prefer += 1 and -= 1 rather than x = x + 1 and x = x - 1 .

Use normal assignment for updating multiple references to avoid accidental mutation.

Following PEP 8 style, augmented assignments should have the same spacing and syntax as normal assignment operators. Just be mindful of potential pitfalls.

Augmented assignment operators provide a compact yet expressive shorthand for modifying variables in Python. They combine an operation and assignment into one atomic expression.

Key takeaways:

Augmented operators perform inplace modification and behave differently than standard operators in some cases.

Know the full list of arithmetic, bitwise, and sequence augmented assignment operators.

Use augmented assignment to write concise and efficient updates to variables and sequences.

Be mindful of right-associativity order of evaluation and behavior with mutable types to avoid bugs.

I hope this guide gives you a comprehensive understanding of augmented assignment in Python. Use these operators appropriately to write clean, idiomatic Python code.

  •    python
  •    variables-and-operators

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in python.

' src=

Last Updated on June 8, 2023 by Prepbytes

single assignment in python

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

  • Career Advice
  • Computer Vision
  • Data Engineering
  • Data Science
  • Language Models
  • Machine Learning
  • Programming
  • Cheat Sheets
  • Recommendations
  • Tech Briefs

5 Common Python Gotchas (And How To Avoid Them)

Explore some of Python’s sharp corners by coding your way through simple yet helpful examples.

5 Common Python Gotchas (And How To Avoid Them)

Python is a beginner-friendly and versatile programming language known for its simplicity and readability. Its elegant syntax, however, is not immune to quirks that can surprise even experienced Python developers. And understanding these is essential for writing bug-free code—or pain-free debugging if you will.

This tutorial explores some of these gotchas: mutable defaults, variable scope in loops and comprehensions, tuple assignment, and more. We’ll code simple examples to see why things work the way they do, and also look at how we can avoid these (if we actually can 🙂). 

So let’s get started!

1. Mutable Defaults

In Python, mutable defaults are common sharp corners. You’ll run into unexpected behavior anytime you define a function with mutable objects, like lists or dictionaries, as default arguments. 

The default value is evaluated only once, when the function is defined, and not each time the function is called . This can lead to unexpected behavior if you mutate the default argument within the function.

Let's take an example:

In this example, add_to_cart is a function that takes an item and appends it to a list cart . The default value of cart is an empty list. Meaning calling the function without an item to add returns an empty cart. 

And here are a couple of function calls:

This works as expected. But what happens now?

Because the default argument is a list—a mutable object—it retains its state between function calls. So each time you call add_to_cart , it appends the value to the same list object created during the function definition. In this example, it’s like all users sharing the same cart.

How To Avoid

As a workaround, you can set cart to None and initialize the cart inside the function like so:

So each user now has a separate cart. 🙂

If you need a refresher on Python functions and function arguments, read Python Function Arguments: A Definitive Guide .

2. Variable Scope in Loops and Comprehensions

Python's scope oddities call for a tutorial of their own. But we’ll look at one such oddity here.

Look at the following snippet:

The variable x is set to 10. But x is also the looping variable. But we’d assume that the looping variable’s scope is limited to the for loop block, yes?

Let’s look at the output:

We see that x is now 4, the final value it takes in the loop, and not the initial value of 10 we set it to.

Now let’s see what happens if we replace the for loop with a comprehension expression:

Here, x is 10, the value we set it to before the comprehension expression:

To avoid unexpected behavior: If you’re using loops, ensure that you don’t name the looping variable the same as another variable you’d want to access later.

3. Integer Identity Quirk

In Python, we use the is keyword for checking object identity. Meaning it checks whether two variables reference the same object in memory. And to check for equality, we use the == operator. Yes?

Now, start a Python REPL and run the following code:

Now run this:

Wait, why does this happen? Well, this is due to "integer caching" or "interning" in CPython, the standard implementation of Python.

CPython caches integer objects in the range of -5 to 256. Meaning every time you use an integer within this range, Python will use the same object in memory. Therefore, when you compare two integers within this range using the is keyword, the result is True because they refer to the same object in memory .

That’s why a is b returns True . You can also verify this by printing out id(a) and id(b) .

However, integers outside this range are not cached. And each occurrence of such integers creates a new object in memory. 

So when you compare two integers outside the cached range using the is keyword (yes, x and y both set to 280 in our example), the result is False because they are indeed two different objects in memory.

This behavior shouldn’t be a problem unless you try to use the is for comparing equality of two objects. So always use the == operator to check if any two Python objects have the same value.

4. Tuple Assignment and Mutable Objects

If you’re familiar with built-in data structures in Python, you know that tuples are immutable . So you cannot modify them in place. Data structures like lists and dictionaries, on the other hand, are mutable . Meaning you can change them in place.

But what about tuples that contain one or more mutable objects?

It's helpful to started a Python REPL and run this simple example:

Here, the first element of the tuple is a list with two elements. We try appending 3 to the first list and it works fine! Well, did we just modify a tuple in place?

Now let’s try to add two more elements to the list, but this time using the += operator:

Yes, you get a TypeError which says the tuple object does not support item assignment. Which is expected. But let’s check the tuple: 

We see that elements 4 and 5 have been added to the list! Did the program just throw an error and succeed at the same time?

Well the += operator internally works by calling the __iadd__() method which performs in-place addition and modifies the list in place. The assignment raises a TypeError exception, but the addition of elements to the end of the list has already succeeded. += is perhaps the sharpest corner!

To avoid such quirks in your program, try using tuples only for immutable collections. And avoid using mutable objects as tuple elements as much as possible.

5. Shallow Copies of Mutable Objects

Mutability has been a recurring topic in our discussion thus far. So here’s another one to wrap up this tutorial.

Sometimes you may need to create independent copies of lists. But what happens when you create a copy using a syntax similar to list2 = list1 where list1 is the original list?

It’s a shallow copy that gets created. So it only copies the references to the original elements of the list. Modifying elements through the shallow copy will affect both the original list and the shallow copy. 

Let's take this example:

We see that the changes to the shallow copy also affect the original list:

Here, we modify the first element of the first nested list in the shallow copy: shallow_copy[0][0] = 100 . But we see that the modification affects both the original list and the shallow copy. 

To avoid this, you can create a deep copy like so:

Now, any modification to the deep copy leaves the original list unchanged.

Wrapping Up

And that’s a wrap! In this tutorial, we've explored several oddities in Python: from the surprising behavior of mutable defaults to the subtleties of shallow copying lists. This is only an introduction to Python’s oddities and is by no means an exhaustive list. You can find all the code examples on GitHub .

As you keep coding for longer in Python—and understand the language better—you’ll perhaps run into many more of these. So, keep coding, keep exploring!

Oh, and let us know in the comments if you’d like to read a sequel to this tutorial.    

Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she's working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.

More On This Topic

  • 3 Crucial Challenges in Conversational AI Development and How to Avoid Them
  • 10 Most Common Data Quality Issues and How to Fix Them
  • KDnuggets News, August 24: Implementing DBSCAN in Python • How to…
  • Most Common Data Science Interview Questions and Answers
  • Common Data Problems (and Solutions)
  • Data Science Programming Languages and When To Use Them

single assignment in python

Get the FREE ebook 'The Great Big Natural Language Processing Primer' and 'The Complete Collection of Data Science Cheat Sheets' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

Latest Posts

  • The Psychology of Data Visualization: How to Present Data that Persuades
  • A Beginner’s Guide to the Top 10 Machine Learning Algorithms
  • A Collection Of Free Data Science Courses From Harvard, Stanford, MIT, Cornell, and Berkeley
  • 5 AI Courses From Google to Advance Your Career
  • Mastering Python for Data Science: Beyond the Basics
  • 10 GitHub Repositories to Master MLOps
  • The 7 Best AI Tools for Data Science Workflow
  • 5 Learning Platforms That Every Techie Should Sign Up To
  • 7 Steps to Mastering Large Language Model Fine-tuning
  • 5 Free Google Courses to Become a Software Engineer

single assignment in python

  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
  • CLR Parser (with Examples)
  • Source to Source Compiler
  • LALR Parser (with Examples)
  • Activation Records
  • SLR Parser (with Examples)
  • Iterative algorithm for a forward data-flow problem
  • Advantages of Multipass Compiler Over Single Pass Compiler
  • Constant Propagation in Compiler Design
  • Directed Acyclic graph in Compiler Design (with examples)
  • Difference between Compiler and Interpreter
  • Lexical Error
  • Applications of Compiler Technology
  • Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
  • What is Handle Pruning?
  • Liveliness Analysis in Compiler Design
  • Symbolic Analysis in Compiler Design
  • Token, Patterns, and Lexemes
  • Parsing ambiguous grammars using LR parser
  • Viable Prefix in Bottom-up Parsing

Static Single Assignment (with relevant examples)

Static Single Assignment was presented in 1988 by Barry K. Rosen, Mark N, Wegman, and F. Kenneth Zadeck. 

In compiler design, Static Single Assignment ( shortened SSA) is a means of structuring the IR (intermediate representation) such that every variable is allotted a value only once and every variable is defined before it’s use. The prime use of SSA is it simplifies and improves the results of compiler optimisation algorithms, simultaneously by simplifying the variable properties. Some Algorithms improved by application of SSA – 

  • Constant Propagation –   Translation of calculations from runtime to compile time. E.g. – the instruction v = 2*7+13 is treated like v = 27
  • Value Range Propagation –   Finding the possible range of values a calculation could result in.
  • Dead Code Elimination – Removing the code which is not accessible and will have no effect on results whatsoever.
  • Strength Reduction – Replacing computationally expensive calculations by inexpensive ones.
  • Register Allocation – Optimising the use of registers for calculations.

Any code can be converted to SSA form by simply replacing the target variable of each code segment with a new variable and substituting each use of a variable with the new edition of the variable reaching that point. Versions are created by splitting the original variables existing in IR and are represented by original name with a subscript such that every variable gets its own version.

Example #1:

Convert the following code segment to SSA form:

Here x,y,z,s,p,q are original variables and x 2 , s 2 , s 3 , s 4 are versions of x and s. 

Example #2:

Here a,b,c,d,e,q,s are original variables and a 2 , q 2 , q 3 are versions of a and q. 

Please Login to comment...

Similar reads.

author

  • CBSE Exam Format Changed for Class 11-12: Focus On Concept Application Questions
  • 10 Best Waze Alternatives in 2024 (Free)
  • 10 Best Squarespace Alternatives in 2024 (Free)
  • Top 10 Owler Alternatives & Competitors in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Variable Assignment in Python

    single assignment in python

  2. Python For Beginners

    single assignment in python

  3. #12 Python Tutorial for Beginners

    single assignment in python

  4. Assigning multiple variables in one line in Python

    single assignment in python

  5. Learn Python Programming Tutorial 4

    single assignment in python

  6. #5 Variables, Assignment statements in Python || Python Course 2020

    single assignment in python

VIDEO

  1. Assignment

  2. Assignment

  3. LECTURE 6: PYTHON DAY 6

  4. Programming Principles Assignment

  5. Grand Assignment

  6. Python

COMMENTS

  1. 7. Simple statements

    An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. Assignment is defined recursively depending on the form of the target (list).

  2. python

    For the future time traveler from Google, here is a new way (available from Python 3.8 onward): b = 1 if a := b: # this section is only reached if b is not 0 or false. # Also, a is set to b print(a, b) This is known as "the walrus operator". More info at the What's New In Python 3.8 page.

  3. Python's Assignment Operator: Write Robust Assignments

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

  4. Different Forms of Assignment Statements in Python

    Assignment creates object references instead of copying the objects. Python creates a variable name the first time when they are assigned a value. Names must be assigned before being referenced. There are some operations that perform assignments implicitly. Assignment statement forms :-. 1. Basic form: Unmute.

  5. Assigning multiple variables in one line in Python

    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 ...

  6. How To Use Assignment Expressions in Python

    The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.. Introduction. Python 3.8, released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called "the walrus operator" because := vaguely resembles a walrus with tusks. ...

  7. Introduction into Python Statements: Assignment, Conditional Examples

    Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result. x = 5. y = x + 3. print(y) In this example, we assign the value 5 to the variable x, then add 3 to x and assign the result ( 8) to the variable y.

  8. Python One Line Conditional Assignment

    Method 1: Ternary Operator. The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative expression y. <OnTrue> if <Condition> else <OnFalse>. Operand.

  9. Unpacking in Python: Beyond Parallel Assignment

    Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list) of variables in a single assignment statement.As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, *.. Historically, Python developers have generically referred to this kind of ...

  10. Python Packing and Unpacking. Mastering The Single Assignment

    The Python Logo from Python.org. Python has a cool feature that permits us to pack and unpack values from iterables in a single assignment. It initially started out as something that was only ...

  11. How to Write the Python if Statement in one Line

    To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line! Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here's the basic structure: if <expression>: <perform_action></perform_action></expression>.

  12. Operators and Expressions in Python

    The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign (=), and it operates on two operands. The left-hand operand is typically a variable, while the right-hand operand is an expression.

  13. Conditional Statements in Python

    In the form shown above: <expr> is an expression evaluated in a Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions in Python tutorial. <statement> is a valid Python statement, which must be indented. (You will see why very soon.) If <expr> is true (evaluates to a value that is "truthy"), then <statement> is executed.

  14. Assignment Operators in Python

    Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. Operator. Description. Syntax = Assign value of right side of expression to left side operand: x = y + z +=

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

    A tuple with one element requires a comma in Python; Swap values in a list or values of variables in Python; Take input from user with input() in Python; Try, except, else, finally in Python (Exception handling) Invert image with Python, Pillow (Negative-positive inversion) Check and add the module search path with sys.path in Python

  16. Python If-Else Statement in One Line

    Pretty basic stuff, so we naturally don't want to spend so many lines of code writing it. As it turns out, you can use the ternary operator in Python to evaluate conditions in a single line. Ternary Operator in Python. A ternary operator exists in some programming languages, and it allows you to shorten a simple If-Else block.

  17. A Comprehensive Guide to Augmented Assignment Operators in Python

    Here x += 3 is equivalent to x = x + 3.The += augmented assignment operator adds the right operand 3 to the current value of x, which is 2.It then assigns the result 5 back to x.. This shorthand allows you to reduce multiple lines of code into a concise single line expression. Some key properties of augmented assignment operators in Python:

  18. Python: multiple assignment vs. individual assignment speed

    Multiple assignment is slower than individual assignment. For example "x,y=a,b" is slower than "x=a; y=b". Curious, I tested it (on Python 2.7): I repeated several times, in different orders, etc., but the multiple assignment snippet consistently performed at least 30% better than the individual assignment.

  19. Assignment Operator in Python

    The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is: variable = value. Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example.

  20. 5 Common Python Gotchas (And How To Avoid Them)

    So always use the == operator to check if any two Python objects have the same value. 4. Tuple Assignment and Mutable Objects . If you're familiar with built-in data structures in Python, you know that tuples are immutable. So you cannot modify them in place. Data structures like lists and dictionaries, on the other hand, are mutable.

  21. Multiple assignment and evaluation order in Python

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

  22. Alek Manoah struggles in rehab start at Single-A

    Manoah struggles with control in Single-A rehab start. NEW YORK -- Alek Manoah started his Minor League rehab assignment down in Single-A Dunedin on Sunday, far from the cold competition at Yankee Stadium, and it didn't go how anyone planned. Manoah walked the first four batters he faced, throwing just two strikes in his first 18 pitches.

  23. Static Single Assignment (with relevant examples)

    Static Single Assignment was presented in 1988 by Barry K. Rosen, Mark N, Wegman, and F. Kenneth Zadeck.. In compiler design, Static Single Assignment ( shortened SSA) is a means of structuring the IR (intermediate representation) such that every variable is allotted a value only once and every variable is defined before it's use. The prime use of SSA is it simplifies and improves the ...

  24. regex

    sums.append(int(match.group(1))) Python for Everybody assignment 11.1 The actual goal is to read a file, look for integers using the re.findall() looking for a regular expression of [0-9]+, then converting the extracted strings to integers and finally summing up the integers. Pycharm is returning: TypeError: int () argument must be a string, a ...