Sign up on Python Hint

Join our community of friendly folks discovering and sharing the latest topics in tech.

We'll never post to any of your accounts without your permission.

How does Python's comma operator work during assignment?

on 10 months ago

The Comma Operator in Python: An Overview

Multiple assignments using commas in python, pitfalls to avoid when using commas in python, conclusion:, port matlab bounding ellipsoid code to python.

31447 views

10 months ago

How to change the dtype of certain columns of a numpy recarray?

95126 views

Numpy meshgrid in 3D

69275 views

11 months ago

svg diagrams using python

55288 views

Why are exceptions within a Python generator not caught?

28377 views

Related Posts

How to get the Worksheet ID from a Google Spreadsheet with python?

Python setup.py: ask for configuration data during setup, how to make the shebang be able to choose the correct python interpreter between python3 and python3.5, how to pass const char* from python to c function, how to use plotly/dash (python) completely offline, python - matplotlib - how do i plot a plane from equation, in django/python, how do i set the memcache to infinite time, how do you reload a module in python version 3.3.2, python 3.4 - library for 2d graphics, failed to load the native tensorflow runtime. python 3.5.2, c++ vs python precision, how can i make my code more readable and dryer when working with xml namespaces in python, how to use python multiprocessing module in django view, calculating power for decimals in python, color logging using logging module in python, installation.

Copyright 2023 - Python Hint

Term of Service

Privacy Policy

Cookie Policy

Unpacking in Python: Beyond Parallel Assignment

python comma separated 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 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

python comma separated assignment

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.

Multiple Assignment Syntax in Python

  • python-tricks

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

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

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

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

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

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

Swapping Values

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

Splitting a List

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

Assigning Multiple Values from a Function

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

Ignoring Values

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

Unpacking Nested Structures

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

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

Extended Unpacking with Slicing

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

Split a String into a List

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

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

5 Best Ways to Split a String and Join with a Comma in Python

💡 Problem Formulation: Let’s discuss how to take a string, split it into a list of substrings based on a delimiter, and then join those substrings into a new string separated by commas. For instance, if our input is “apple orange banana”, the desired output would be “apple,orange,banana”. This is a common data manipulation task that can be accomplished in many ways in Python.

Method 1: Using the split() and join() Methods

This method involves utilizing the built-in split() method to divide the string into a list of substrings and then employing the join() method to concatenate those substrings with a comma. This is a straightforward and Pythonic approach to accomplish the task.

Here’s an example:

The code snippet splits a string into a list using spaces as the delimiter, and then rejoins the elements of the list into a string with commas as separators. It’s an efficient two-step transformation that is easily readable and maintainable.

Method 2: Using List Comprehension

List comprehension provides an elegant and concise way to combine the operations of splitting and joining. By iterating over each element resulting from the split() method within a list comprehension, you can apply transformations before joining the elements.

This snippet leverages list comprehension to split the string and then immediately join the list elements with a comma. This method condenses the operation into a single line without compromising readability.

Method 3: Using Regular Expressions

Regular expressions are a powerful tool for string manipulation. By using the re module, we can define a pattern to split the string, which can be helpful when the string contains inconsistent delimiters.

The code uses the re.split() function to split the initial string into a list using a regex pattern that matches commas or whitespace, with potential extra whitespace around them. It then joins the list with commas to achieve the desired result.

Method 4: Using the replace() Method

If your string uses a consistent separator that you wish to replace with a comma, Python’s replace() method can directly substitute the old separator with the new one.

In this snippet, the replace() method is used to directly transform spaces into commas, offering a quick solution when dealing with consistent separators.

Bonus One-Liner Method 5: Using the translate() Method

The translate() method can be used to replace characters in a string. Combined with the str.maketrans() function, it offers a one-liner approach to replacing spaces with commas.

This snippet utilizes the translate() method together with str.maketrans() to create a translation table, which replaces every space with a comma. It’s a less commonly used but effective one-liner.

Summary/Discussion

  • Method 1: split() and join() . Strengths: Pythonic and straightforward. Weaknesses: Requires a consistent separator for splitting.
  • Method 2: List Comprehension. Strengths: Compact and elegant. Weaknesses: Overkill for simple transformations and less performant for very large lists.
  • Method 3: Regular Expressions. Strengths: Highly flexible and powerful for complex patterns. Weaknesses: Can be overcomplicated for simple tasks and slower than other methods.
  • Method 4: replace() Method. Strengths: Simple and quick for consistent separators. Weaknesses: Not suitable for variable separators.
  • Method 5: translate() Method. Strengths: Efficient one-liner. Weaknesses: Can be obscure and less readable to those unfamiliar with the method.

Emily Rosemary Collins is a tech enthusiast with a strong background in computer science, always staying up-to-date with the latest trends and innovations. Apart from her love for technology, Emily enjoys exploring the great outdoors, participating in local community events, and dedicating her free time to painting and photography. Her interests and passion for personal growth make her an engaging conversationalist and a reliable source of knowledge in the ever-evolving world of technology.

  • Python »
  • 3.12.2 Documentation »
  • The Python Language Reference »
  • 8. Compound statements
  • Theme Auto Light Dark |

8. Compound statements ¶

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.

The if , while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements.

A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print() calls are executed:

Summarizing:

Note that statements always end in a NEWLINE possibly followed by a DEDENT . Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling else ’ problem is solved in Python by requiring nested if statements to be indented).

The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.

8.1. The if statement ¶

The if statement is used for conditional execution:

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.

8.2. The while statement ¶

The while statement is used for repeated execution as long as an expression is true:

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

8.3. The for statement ¶

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

The starred_list expression is evaluated once; it should yield an iterable object. An iterator is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Assignment statements ), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.

The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:

Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type range() represents immutable arithmetic sequences of integers. For instance, iterating range(3) successively yields 0, 1, and then 2.

Changed in version 3.11: Starred elements are now allowed in the expression list.

8.4. The try statement ¶

The try statement specifies exception handlers and/or cleanup code for a group of statements:

Additional information on exceptions can be found in section Exceptions , and information on using the raise statement to generate exceptions may be found in section The raise statement .

8.4.1. except clause ¶

The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if the object is the class or a non-virtual base class of the exception object, or a tuple containing an item that is the class or a non-virtual base class of the exception object.

If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. [ 1 ]

If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception).

When a matching except clause is found, the exception is assigned to the target specified after the as keyword in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

When an exception has been assigned using as target , it is cleared at the end of the except clause. This is as if

was translated to

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

Before an except clause’s suite is executed, the exception is stored in the sys module, where it can be accessed from within the body of the except clause by calling sys.exception() . When leaving an exception handler, the exception stored in the sys module is reset to its previous value:

8.4.2. except* clause ¶

The except* clause(s) are used for handling ExceptionGroup s. The exception type for matching is interpreted as in the case of except , but in the case of exception groups we can have partial matches when the type matches some of the exceptions in the group. This means that multiple except* clauses can execute, each handling part of the exception group. Each clause executes at most once and handles an exception group of all matching exceptions. Each exception in the group is handled by at most one except* clause, the first that matches it.

Any remaining exceptions that were not handled by any except* clause are re-raised at the end, along with all exceptions that were raised from within the except* clauses. If this list contains more than one exception to reraise, they are combined into an exception group.

If the raised exception is not an exception group and its type matches one of the except* clauses, it is caught and wrapped by an exception group with an empty message string.

An except* clause must have a matching type, and this type cannot be a subclass of BaseExceptionGroup . It is not possible to mix except and except* in the same try . break , continue and return cannot appear in an except* clause.

8.4.3. else clause ¶

The optional else clause is executed if the control flow leaves the try suite, no exception was raised, and no return , continue , or break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses.

8.4.4. finally clause ¶

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return , break or continue statement, the saved exception is discarded:

The exception information is not available to the program during execution of the finally clause.

When a return , break or continue statement is executed in the try suite of a try … finally statement, the finally clause is also executed ‘on the way out.’

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

Changed in version 3.8: Prior to Python 3.8, a continue statement was illegal in the finally clause due to a problem with the implementation.

8.5. The with statement ¶

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers ). This allows common try … except … finally usage patterns to be encapsulated for convenient reuse.

The execution of the with statement with one “item” proceeds as follows:

The context expression (the expression given in the with_item ) is evaluated to obtain a context manager.

The context manager’s __enter__() is loaded for later use.

The context manager’s __exit__() is loaded for later use.

The context manager’s __enter__() method is invoked.

If a target was included in the with statement, the return value from __enter__() is assigned to it.

The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 7 below.

The suite is executed.

The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__() . Otherwise, three None arguments are supplied.

If the suite was exited due to an exception, and the return value from the __exit__() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and execution proceeds at the normal location for the kind of exit that was taken.

The following code:

is semantically equivalent to:

With more than one item, the context managers are processed as if multiple with statements were nested:

You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. For example:

Changed in version 3.1: Support for multiple context expressions.

Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines.

The specification, background, and examples for the Python with statement.

8.6. The match statement ¶

New in version 3.10.

The match statement is used for pattern matching. Syntax:

This section uses single quotes to denote soft keywords .

Pattern matching takes a pattern as input (following case ) and a subject value (following match ). The pattern (which may contain subpatterns) is matched against the subject value. The outcomes are:

A match success or failure (also termed a pattern success or failure).

Possible binding of matched values to a name. The prerequisites for this are further discussed below.

The match and case keywords are soft keywords .

PEP 634 – Structural Pattern Matching: Specification

PEP 636 – Structural Pattern Matching: Tutorial

8.6.1. Overview ¶

Here’s an overview of the logical flow of a match statement:

The subject expression subject_expr is evaluated and a resulting subject value obtained. If the subject expression contains a comma, a tuple is constructed using the standard rules .

Each pattern in a case_block is attempted to match with the subject value. The specific rules for success or failure are described below. The match attempt can also bind some or all of the standalone names within the pattern. The precise pattern binding rules vary per pattern type and are specified below. Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement .

During failed pattern matches, some subpatterns may succeed. Do not rely on bindings being made for a failed match. Conversely, do not rely on variables remaining unchanged after a failed match. The exact behavior is dependent on implementation and may vary. This is an intentional decision made to allow different implementations to add optimizations.

If the pattern succeeds, the corresponding guard (if present) is evaluated. In this case all name bindings are guaranteed to have happened.

If the guard evaluates as true or is missing, the block inside case_block is executed.

Otherwise, the next case_block is attempted as described above.

If there are no further case blocks, the match statement is completed.

Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.

A sample match statement:

In this case, if flag is a guard. Read more about that in the next section.

8.6.2. Guards ¶

A guard (which is part of the case ) must succeed for code inside the case block to execute. It takes the form: if followed by an expression.

The logical flow of a case block with a guard follows:

Check that the pattern in the case block succeeded. If the pattern failed, the guard is not evaluated and the next case block is checked.

If the pattern succeeded, evaluate the guard .

If the guard condition evaluates as true, the case block is selected.

If the guard condition evaluates as false, the case block is not selected.

If the guard raises an exception during evaluation, the exception bubbles up.

Guards are allowed to have side effects as they are expressions. Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don’t all succeed. (I.e., guard evaluation must happen in order.) Guard evaluation must stop once a case block is selected.

8.6.3. Irrefutable Case Blocks ¶

An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last.

A case block is considered irrefutable if it has no guard and its pattern is irrefutable. A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed. Only the following patterns are irrefutable:

AS Patterns whose left-hand side is irrefutable

OR Patterns containing at least one irrefutable pattern

Capture Patterns

Wildcard Patterns

parenthesized irrefutable patterns

8.6.4. Patterns ¶

This section uses grammar notations beyond standard EBNF:

the notation SEP.RULE+ is shorthand for RULE (SEP RULE)*

the notation !RULE is shorthand for a negative lookahead assertion

The top-level syntax for patterns is:

The descriptions below will include a description “in simple terms” of what a pattern does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). Note that these descriptions are purely for illustration purposes and may not reflect the underlying implementation. Furthermore, they do not cover all valid forms.

8.6.4.1. OR Patterns ¶

An OR pattern is two or more patterns separated by vertical bars | . Syntax:

Only the final subpattern may be irrefutable , and each subpattern must bind the same set of names to avoid ambiguity.

An OR pattern matches each of its subpatterns in turn to the subject value, until one succeeds. The OR pattern is then considered successful. Otherwise, if none of the subpatterns succeed, the OR pattern fails.

In simple terms, P1 | P2 | ... will try to match P1 , if it fails it will try to match P2 , succeeding immediately if any succeeds, failing otherwise.

8.6.4.2. AS Patterns ¶

An AS pattern matches an OR pattern on the left of the as keyword against a subject. Syntax:

If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds the subject to the name on the right of the as keyword and succeeds. capture_pattern cannot be a _ .

In simple terms P as NAME will match with P , and on success it will set NAME = <subject> .

8.6.4.3. Literal Patterns ¶

A literal pattern corresponds to most literals in Python. Syntax:

The rule strings and the token NUMBER are defined in the standard Python grammar . Triple-quoted strings are supported. Raw strings and byte strings are supported. f-strings are not supported.

The forms signed_number '+' NUMBER and signed_number '-' NUMBER are for expressing complex numbers ; they require a real number on the left and an imaginary number on the right. E.g. 3 + 4j .

In simple terms, LITERAL will succeed only if <subject> == LITERAL . For the singletons None , True and False , the is operator is used.

8.6.4.4. Capture Patterns ¶

A capture pattern binds the subject value to a name. Syntax:

A single underscore _ is not a capture pattern (this is what !'_' expresses). It is instead treated as a wildcard_pattern .

In a given pattern, a given name can only be bound once. E.g. case x, x: ... is invalid while case [x] | x: ... is allowed.

Capture patterns always succeed. The binding follows scoping rules established by the assignment expression operator in PEP 572 ; the name becomes a local variable in the closest containing function scope unless there’s an applicable global or nonlocal statement.

In simple terms NAME will always succeed and it will set NAME = <subject> .

8.6.4.5. Wildcard Patterns ¶

A wildcard pattern always succeeds (matches anything) and binds no name. Syntax:

_ is a soft keyword within any pattern, but only within patterns. It is an identifier, as usual, even within match subject expressions, guard s, and case blocks.

In simple terms, _ will always succeed.

8.6.4.6. Value Patterns ¶

A value pattern represents a named value in Python. Syntax:

The dotted name in the pattern is looked up using standard Python name resolution rules . The pattern succeeds if the value found compares equal to the subject value (using the == equality operator).

In simple terms NAME1.NAME2 will succeed only if <subject> == NAME1.NAME2

If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. This cache is strictly tied to a given execution of a given match statement.

8.6.4.7. Group Patterns ¶

A group pattern allows users to add parentheses around patterns to emphasize the intended grouping. Otherwise, it has no additional syntax. Syntax:

In simple terms (P) has the same effect as P .

8.6.4.8. Sequence Patterns ¶

A sequence pattern contains several subpatterns to be matched against sequence elements. The syntax is similar to the unpacking of a list or tuple.

There is no difference if parentheses or square brackets are used for sequence patterns (i.e. (...) vs [...] ).

A single pattern enclosed in parentheses without a trailing comma (e.g. (3 | 4) ) is a group pattern . While a single pattern enclosed in square brackets (e.g. [3 | 4] ) is still a sequence pattern.

At most one star subpattern may be in a sequence pattern. The star subpattern may occur in any position. If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern.

The following is the logical flow for matching a sequence pattern against a subject value:

If the subject value is not a sequence [ 2 ] , the sequence pattern fails.

If the subject value is an instance of str , bytes or bytearray the sequence pattern fails.

The subsequent steps depend on whether the sequence pattern is fixed or variable-length.

If the sequence pattern is fixed-length:

If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails

Subpatterns in the sequence pattern are matched to their corresponding items in the subject sequence from left to right. Matching stops as soon as a subpattern fails. If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds.

Otherwise, if the sequence pattern is variable-length:

If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.

The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.

If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.

Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.

The length of the subject sequence is obtained via len() (i.e. via the __len__() protocol). This length may be cached by the interpreter in a similar manner as value patterns .

In simple terms [P1, P2, P3, … , P<N>] matches only if all the following happens:

check <subject> is a sequence

len(subject) == <N>

P1 matches <subject>[0] (note that this match can also bind names)

P2 matches <subject>[1] (note that this match can also bind names)

… and so on for the corresponding pattern/element.

8.6.4.9. Mapping Patterns ¶

A mapping pattern contains one or more key-value patterns. The syntax is similar to the construction of a dictionary. Syntax:

At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern.

Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will raise a SyntaxError . Two keys that otherwise have the same value will raise a ValueError at runtime.

The following is the logical flow for matching a mapping pattern against a subject value:

If the subject value is not a mapping [ 3 ] ,the mapping pattern fails.

If every key given in the mapping pattern is present in the subject mapping, and the pattern for each key matches the corresponding item of the subject mapping, the mapping pattern succeeds.

If duplicate keys are detected in the mapping pattern, the pattern is considered invalid. A SyntaxError is raised for duplicate literal values; or a ValueError for named keys of the same value.

Key-value pairs are matched using the two-argument form of the mapping subject’s get() method. Matched key-value pairs must already be present in the mapping, and not created on-the-fly via __missing__() or __getitem__() .

In simple terms {KEY1: P1, KEY2: P2, ... } matches only if all the following happens:

check <subject> is a mapping

KEY1 in <subject>

P1 matches <subject>[KEY1]

… and so on for the corresponding KEY/pattern pair.

8.6.4.10. Class Patterns ¶

A class pattern represents a class and its positional and keyword arguments (if any). Syntax:

The same keyword should not be repeated in class patterns.

The following is the logical flow for matching a class pattern against a subject value:

If name_or_attr is not an instance of the builtin type , raise TypeError .

If the subject value is not an instance of name_or_attr (tested via isinstance() ), the class pattern fails.

If no pattern arguments are present, the pattern succeeds. Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present.

For a number of built-in types (specified below), a single positional subpattern is accepted which will match the entire subject; for these types keyword patterns also work as for other types.

If only keyword patterns are present, they are processed as follows, one by one:

I. The keyword is looked up as an attribute on the subject.

If this raises an exception other than AttributeError , the exception bubbles up. If this raises AttributeError , the class pattern has failed. Else, the subpattern associated with the keyword pattern is matched against the subject’s attribute value. If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword.

II. If all keyword patterns succeed, the class pattern succeeds.

If any positional patterns are present, they are converted to keyword patterns using the __match_args__ attribute on the class name_or_attr before matching:

I. The equivalent of getattr(cls, "__match_args__", ()) is called.

If this raises an exception, the exception bubbles up. If the returned value is not a tuple, the conversion fails and TypeError is raised. If there are more positional patterns than len(cls.__match_args__) , TypeError is raised. Otherwise, positional pattern i is converted to a keyword pattern using __match_args__[i] as the keyword. __match_args__[i] must be a string; if not TypeError is raised. If there are duplicate keywords, TypeError is raised. See also Customizing positional arguments in class pattern matching

the match proceeds as if there were only keyword patterns.

For the following built-in types the handling of positional subpatterns is different:

These classes accept a single positional argument, and the pattern there is matched against the whole object rather than an attribute. For example int(0|1) matches the value 0 , but not the value 0.0 .

In simple terms CLS(P1, attr=P2) matches only if the following happens:

isinstance(<subject>, CLS)

convert P1 to a keyword pattern using CLS.__match_args__

For each keyword argument attr=P2 :

hasattr(<subject>, "attr")

P2 matches <subject>.attr

… and so on for the corresponding keyword argument/pattern pair.

8.7. Function definitions ¶

A function definition defines a user-defined function object (see section The standard type hierarchy ):

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.

The function definition does not execute the function body; this gets executed only when the function is called. [ 4 ]

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code

is roughly equivalent to

except that the original function is not temporarily bound to the name func .

Changed in version 3.9: Functions may be decorated with any valid assignment_expression . Previously, the grammar was much more restrictive; see PEP 614 for details.

A list of type parameters may be given in square brackets between the function’s name and the opening parenthesis for its parameter list. This indicates to static type checkers that the function is generic. At runtime, the type parameters can be retrieved from the function’s __type_params__ attribute. See Generic functions for more.

Changed in version 3.12: Type parameter lists are new in Python 3.12.

When one or more parameters have the form parameter = expression , the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “ * ” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter value is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default parameter value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

Function call semantics are described in more detail in section Calls . A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default values. If the form “ *identifier ” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “ **identifier ” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “ * ” or “ *identifier ” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “ / ” are positional-only parameters and may only be passed by positional arguments.

Changed in version 3.8: The / function parameter syntax may be used to indicate positional-only parameters. See PEP 570 for details.

Parameters may have an annotation of the form “ : expression ” following the parameter name. Any parameter may have an annotation, even those of the form *identifier or **identifier . Functions may have “return” annotation of the form “ -> expression ” after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__ attribute of the function object. If the annotations import from __future__ is used, annotations are preserved as strings at runtime which enables postponed evaluation. Otherwise, they are evaluated when the function definition is executed. In this case annotations may be evaluated in a different order than they appear in the source code.

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section Lambdas . Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “ def ” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “ def ” form is actually more powerful since it allows the execution of multiple statements and annotations.

Programmer’s note: Functions are first-class objects. A “ def ” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

The original specification for function annotations.

Definition of a standard meaning for annotations: type hints.

Ability to type hint variable declarations, including class variables and instance variables.

Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation.

Function and method decorators were introduced. Class decorators were introduced in PEP 3129 .

8.8. Class definitions ¶

A class definition defines a class object (see section The standard type hierarchy ):

A class definition is an executable statement. The inheritance list usually gives a list of base classes (see Metaclasses for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class object ; hence,

is equivalent to

The class’s suite is then executed in a new execution frame (see Naming and binding ), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [ 5 ] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

The order in which attributes are defined in the class body is preserved in the new class’s __dict__ . Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax.

Class creation can be customized heavily using metaclasses .

Classes can also be decorated: just like when decorating functions,

The evaluation rules for the decorator expressions are the same as for function decorators. The result is then bound to the class name.

Changed in version 3.9: Classes may be decorated with any valid assignment_expression . Previously, the grammar was much more restrictive; see PEP 614 for details.

A list of type parameters may be given in square brackets immediately after the class’s name. This indicates to static type checkers that the class is generic. At runtime, the type parameters can be retrieved from the class’s __type_params__ attribute. See Generic classes for more.

Programmer’s note: Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with self.name = value . Both class and instance attributes are accessible through the notation “ self.name ”, and an instance attribute hides a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable values there can lead to unexpected results. Descriptors can be used to create instance variables with different implementation details.

The proposal that changed the declaration of metaclasses to the current syntax, and the semantics for how classes with metaclasses are constructed.

The proposal that added class decorators. Function and method decorators were introduced in PEP 318 .

8.9. Coroutines ¶

New in version 3.5.

8.9.1. Coroutine function definition ¶

Execution of Python coroutines can be suspended and resumed at many points (see coroutine ). await expressions, async for and async with can only be used in the body of a coroutine function.

Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.

It is a SyntaxError to use a yield from expression inside the body of a coroutine function.

An example of a coroutine function:

Changed in version 3.7: await and async are now keywords; previously they were only treated as such inside the body of a coroutine function.

8.9.2. The async for statement ¶

An asynchronous iterable provides an __aiter__ method that directly returns an asynchronous iterator , which can call asynchronous code in its __anext__ method.

The async for statement allows convenient iteration over asynchronous iterables.

Is semantically equivalent to:

See also __aiter__() and __anext__() for details.

It is a SyntaxError to use an async for statement outside the body of a coroutine function.

8.9.3. The async with statement ¶

An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.

See also __aenter__() and __aexit__() for details.

It is a SyntaxError to use an async with statement outside the body of a coroutine function.

The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax.

8.10. Type parameter lists ¶

New in version 3.12.

Functions (including coroutines ), classes and type aliases may contain a type parameter list:

Semantically, this indicates that the function, class, or type alias is generic over a type variable. This information is primarily used by static type checkers, and at runtime, generic objects behave much like their non-generic counterparts.

Type parameters are declared in square brackets ( [] ) immediately after the name of the function, class, or type alias. The type parameters are accessible within the scope of the generic object, but not elsewhere. Thus, after a declaration def func[T](): pass , the name T is not available in the module scope. Below, the semantics of generic objects are described with more precision. The scope of type parameters is modeled with a special function (technically, an annotation scope ) that wraps the creation of the generic object.

Generic functions, classes, and type aliases have a __type_params__ attribute listing their type parameters.

Type parameters come in three kinds:

typing.TypeVar , introduced by a plain name (e.g., T ). Semantically, this represents a single type to a type checker.

typing.TypeVarTuple , introduced by a name prefixed with a single asterisk (e.g., *Ts ). Semantically, this stands for a tuple of any number of types.

typing.ParamSpec , introduced by a name prefixed with two asterisks (e.g., **P ). Semantically, this stands for the parameters of a callable.

typing.TypeVar declarations can define bounds and constraints with a colon ( : ) followed by an expression. A single expression after the colon indicates a bound (e.g. T: int ). Semantically, this means that the typing.TypeVar can only represent types that are a subtype of this bound. A parenthesized tuple of expressions after the colon indicates a set of constraints (e.g. T: (str, bytes) ). Each member of the tuple should be a type (again, this is not enforced at runtime). Constrained type variables can only take on one of the types in the list of constraints.

For typing.TypeVar s declared using the type parameter list syntax, the bound and constraints are not evaluated when the generic object is created, but only when the value is explicitly accessed through the attributes __bound__ and __constraints__ . To accomplish this, the bounds or constraints are evaluated in a separate annotation scope .

typing.TypeVarTuple s and typing.ParamSpec s cannot have bounds or constraints.

The following example indicates the full set of allowed type parameter declarations:

8.10.1. Generic functions ¶

Generic functions are declared as follows:

This syntax is equivalent to:

Here annotation-def indicates an annotation scope , which is not actually bound to any name at runtime. (One other liberty is taken in the translation: the syntax does not go through attribute access on the typing module, but creates an instance of typing.TypeVar directly.)

The annotations of generic functions are evaluated within the annotation scope used for declaring the type parameters, but the function’s defaults and decorators are not.

The following example illustrates the scoping rules for these cases, as well as for additional flavors of type parameters:

Except for the lazy evaluation of the TypeVar bound, this is equivalent to:

The capitalized names like DEFAULT_OF_arg are not actually bound at runtime.

8.10.2. Generic classes ¶

Generic classes are declared as follows:

Here again annotation-def (not a real keyword) indicates an annotation scope , and the name TYPE_PARAMS_OF_Bag is not actually bound at runtime.

Generic classes implicitly inherit from typing.Generic . The base classes and keyword arguments of generic classes are evaluated within the type scope for the type parameters, and decorators are evaluated outside that scope. This is illustrated by this example:

This is equivalent to:

8.10.3. Generic type aliases ¶

The type statement can also be used to create a generic type alias:

Except for the lazy evaluation of the value, this is equivalent to:

Here, annotation-def (not a real keyword) indicates an annotation scope . The capitalized names like TYPE_PARAMS_OF_ListOrSet are not actually bound at runtime.

Table of Contents

  • 8.1. The if statement
  • 8.2. The while statement
  • 8.3. The for statement
  • 8.4.1. except clause
  • 8.4.2. except* clause
  • 8.4.3. else clause
  • 8.4.4. finally clause
  • 8.5. The with statement
  • 8.6.1. Overview
  • 8.6.2. Guards
  • 8.6.3. Irrefutable Case Blocks
  • 8.6.4.1. OR Patterns
  • 8.6.4.2. AS Patterns
  • 8.6.4.3. Literal Patterns
  • 8.6.4.4. Capture Patterns
  • 8.6.4.5. Wildcard Patterns
  • 8.6.4.6. Value Patterns
  • 8.6.4.7. Group Patterns
  • 8.6.4.8. Sequence Patterns
  • 8.6.4.9. Mapping Patterns
  • 8.6.4.10. Class Patterns
  • 8.7. Function definitions
  • 8.8. Class definitions
  • 8.9.1. Coroutine function definition
  • 8.9.2. The async for statement
  • 8.9.3. The async with statement
  • 8.10.1. Generic functions
  • 8.10.2. Generic classes
  • 8.10.3. Generic type aliases

Previous topic

7. Simple statements

9. Top-level components

  • Report a Bug
  • Show Source

Python Examples

  • Online Python Compiler
  • Hello World
  • Console Operations
  • Conditional Statements
  • Loop Statements
  • Builtin Functions
  • Type Conversion

Collections

  • Classes and Objects
  • File Operations
  • Global Variables
  • Regular Expressions
  • Multi-threading
  • phonenumbers
  • Breadcrumbs
  • ► Python Examples
  • ► ► String Tutorials
  • ► ► ► Python Split String by Comma
  • Python Operators
  • Python String Tutorials
  • Python String
  • Python String Operations
  • Python String Methods
  • Python - Create string
  • Python - Create string using single quotes
  • Python - Create string using double quotes
  • Python - Create string using str() builtin function
  • Python - Create multiline string
  • Python - Create empty string
  • Python - Create string of specific length
  • Python - Create string from list
  • Python - Create string from list of characters
  • Python - Create string from integer
  • Python - Create string from variable
  • Python - Create string from two variables
  • String Basics
  • Python - String length
  • Python - Substring of a string
  • Python - Slice a string
  • Python - List of strings
  • Python - Check if all strings in a list are not empty
  • Python - Print unique characters present in string
  • Python - Check if string is empty
  • Read / Print
  • Python - Read string from console
  • Python - Print String to Console Output
  • Python string - Get character at specific index
  • Python string - Get first character
  • Python string - Get last character
  • Python string - Get first n characters
  • Python string - Get last n characters
  • Python - Get substring after specific character
  • Python - Get substring before specific character
  • Python - Get substring between two specific characters
  • Python - Get substring between brackets
  • Python - Get substring from specific index to end
  • Python string - Iterate over characters
  • Python string - Iterate over words
  • Python - Check if string contains only alphabets
  • Python - Check if string contains only alphanumeric
  • Python - Check if string value is numeric
  • Python - Check if string contains substring
  • Python - Check if string contains substring from list
  • Python - Check if string contains specific character
  • Python - Check if specific character is present in string
  • Python - Check if string is an integer
  • Python - Check if string is a float value
  • Python - Check if string is a number
  • Python - Check if all strings in list are not empty
  • Python - Check if string starts with specific prefix
  • Python - Check if string ends with specific suffix
  • Replacements
  • Python - Replace substring
  • Python string - Replace multiple spaces with single space
  • Python string - Replace character at specific index
  • Python string - Replace first occurrence
  • Python string - Replace last occurrence
  • Python string - Replace first n occurrences
  • Python string - Replace from dictionary
  • Python string - Replace using regular expression
  • Python string - Replace forward slash with backward slash
  • Append/Concatenate/Insert
  • Python string - Append
  • Python string - Append a character to end
  • Python string - Append new line
  • Python string - Append number
  • Python string - Append in loop
  • Python string - Append variable
  • Python string - Append to a string variable
  • Python string - Concatenate
  • Python - Repeat string N times
  • Python string - Insert character at start
  • Python string - Insert character at specific index
  • Python - Insert string at specific position
  • Python string - Replace all occurrences
  • Python - Split string
  • Python - Split string into specific length chunks
  • Python - Split string by underscore
  • Python - Split string by space
  • Python - Split string by new line
  • Python - Split string by comma
  • Python - Split string into characters
  • Python - Split string into N equal parts
  • Python - Split string into lines
  • Python - Split string in half
  • Python - Split string by regular expression
  • Sorting Operations
  • Python - Sort List of Strings
  • Python - Sort Characters in String
  • Transformations
  • Python - Convert string to lowercase
  • Python - Convert string to uppercase
  • Python - Remove white spaces at start and end of string
  • Python - Capitalise first character of string
  • Python - Reverse string
  • Python - Center a string in specific length
  • Delete Operations
  • Python String - Remove character at specific index
  • Python String - Remove first character
  • Python String - Remove last character
  • Python String - Remove substring
  • Python String - Remove specific character
  • Python String - Remove first and last character
  • Python String - Remove first n characters
  • Python String - Remove last n characters
  • Python String - Remove first line
  • Python String - Remove spaces
  • Python String - Remove special characters
  • Conversions
  • Python - Convert string to int
  • Python - Convert string to float
  • Python - Convert string to list of characters
  • Python - Convert string to list
  • Python - Convert string to dictionary
  • Python - Convert int to string
  • Python - Convert float to string
  • Python - Convert list of characters to string
  • Python - Convert bytes to string
  • Python - Check if two strings are equal
  • Python - Check if two strings are equal ignore case
  • Python - Compare strings
  • Python strings - Compare first n characters
  • Python strings - Compare first character
  • Python strings - Compare last character
  • Python strings - Compare nth character
  • Python - Find character in first string that are not present in second string
  • Python - Find characters that are common to given strings
  • Python - Find index of substring in a string
  • Python - Find number of occurrences of substring in string
  • Python - Find number of overlapping occurrences of substring in string
  • Python - Find index of first occurrence of substring in string
  • Python - Find index of last occurrence of substring in string
  • Python - Find index of Nth occurrence of substring in string
  • Python - Find longest common prefix string
  • Python - Variables in string
  • Python - Escape single quote inside string
  • Python - Escape double quotes inside string
  • Python - Escape backslash inside string
  • Python - Write string with new line
  • Python - Print new line after variable
  • Exceptions with string data
  • Python NameError: name 'string' is not defined
  • String methods
  • Python String capitalize()
  • Python String casefold()
  • Python String center()
  • Python String count()
  • Python String endswith()
  • Python String find()
  • Python String index()
  • Python String isalnum()
  • Python String isalpha()
  • Python String isascii()
  • Python String isdecimal()
  • Python String isdigit()
  • Python String isidentifier()
  • Python String islower()
  • Python String isnumeric()
  • Python String isspace()
  • Python String istitle()
  • Python String isupper()
  • Python String join()
  • Python String lower()
  • Python String lstrip()
  • Python String maketrans()
  • Python String partition()
  • Python String removeprefix()
  • Python String removesuffix()
  • Python string replace()
  • Python String rstrip()
  • Python String split()
  • Python string splitlines()
  • Python String startswith()
  • Python String strip()
  • Python String swapcase()
  • Python String title()
  • Python String translate()
  • Python String upper()
  • Other String tutorials
  • Python - Find next character for given character in ASCII
  • Python Escape characters
  • Python - Get all possible substrings of a string
  • Python - Get k length substrings of a string
  • Python Functions

Python Split String by Comma

  • Split given string by comma
  • Split given string by one or more commas

Python – Split String by Comma

You can split a string in Python with the string formed by the chunks and commas separating them.

In this tutorial, we will learn how to split a string by comma , in Python using String.split() .

1. Split given string by comma

In this example, we will take a string with chunks separated by comma , , split the string and store the items in a list.

Python Program

2. Split given string by one or more commas

If you use String.split() on String with more than one comma coming adjacent to each other, you would get empty chunks. An example is shown below.

In this example, we will take a string with chunks separated by one or more underscore characters, split the string and store the chunk in a list, without any empty items.

We shall use re python package in the following program. re.split(regular_expression, string) returns list of items split from string based on the regular_expression .

Regular Expression ,+ represents one or more commas. So, one or more commas is considered as a delimiter.

One ore more adjacent commas is considered as a single delimiter.

In this tutorial of Python Examples , we learned how to split a string by comma using String.split() and re.split() methods.

Related Tutorials

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python Program that Displays Letters that are not common in two strings
  • Python - Integers String to Integer List
  • Python - Character Replacement Combination
  • Python - String uncommon characters
  • Python | Ways to split strings using newline delimiter
  • Python - Characters Index occurrences in String
  • Python - Split a String by Custom Lengths
  • Python - Test substring order
  • Python - Right and Left Shift characters in String
  • Python program to extract numeric suffix from string
  • Python | Check whether string contains only numbers or not
  • Python | Get numeric prefix of given string
  • Python - Check if Elements delimited by K
  • Python - Maximum occurring Substring from list
  • Python - Convert Delimiter separated list to Number
  • Python - Case insensitive string replacement
  • Python | Check if string ends with any string in given list
  • Python - Specific Characters Frequency in String List
  • Python - Construct Grades List

Python – Custom Split Comma Separated Words

While working with Python, we can have problem in which we need to perform the task of splitting the words of string on spaces. But sometimes, we can have comma separated words, which have comma’s joined to words and require to split them separately. Lets discuss certain ways in which this task can be performed.

Method #1 : Using replace()  

Using replace() is one way to solve this problem. In this, we just separate the joined comma from string to spaced so that they can be splitted along with other words correctly.

Time complexity: O(n), where n is the length of the input string. Auxiliary space: O(n), where n is the length of the input string.

Method #2 : Using re.findall()  

This problem can also be used using regex. In this, we find the occurrences of non space word and perform a split on that basis.

Time Complexity: O(n) Auxiliary Space: O(n)

Method 3 – Custom Split Comma Separated Words Using String split() Method.

In this method to achieve the same result is by using the string split() method. we can split the string based on the comma separator, and then strip any whitespace characters from each resulting substring.

Time complexity: O(n), where n is the length of the input string test_str. Auxiliary space: O(n), where n is the length of the input string test_str.

Method #4: Using list comprehension

This program splits a string into words using the comma as a delimiter, and then removes any leading or trailing whitespace from each word using a list comprehension. The resulting list of stripped words is then printed.

Time complexity: O(n), where n is the length of the input string.  Auxiliary space: O(n), where n is the length of the input string.

Method #5: Using the string.split() method

Time complexity: O(n), where n is the length of the input string, test_str.  Auxiliary space: O(n), where n is the length of the input string, test_str.

Method #6: Using the re.split() method from the re module

One additional method for splitting comma-separated words in Python is using the re.split() method from the re module.

Step-by-step approach:

  • Import the re module .
  • Initialize the string to be split, test_str . Define a regular expression pattern that matches commas followed by any number of spaces (“,\s*”).
  • Use the re.split() method with the regular expression pattern to split the string.
  • Print the resulting list of split strings.

Below is the implementation of the above approach:

Time complexity: O(n), where n is the length of the input string. Auxiliary space: O(n), where n is the length of the input string. In the best case, where the input string contains only one comma, the space complexity is O(1).

Please Login to comment...

author

  • Python string-programs
  • 10 Best Free Social Media Management and Marketing Apps for Android - 2024
  • 10 Best Customer Database Software of 2024
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

VIDEO

  1. How to use assignment operators in #python

  2. Assignment Operators in Python

  3. Python's Assignment 2

  4. Assignment Operators in python #python #operator

  5. Week 3 graded assignment python #python #iitm

  6. Is Python's += operator the same as = and +?

COMMENTS

  1. python

    a = b. b = t. In general if you have a comma-separated list of variables left of the assignment operator and an expression that generates a tuple, the tuple is unpacked and stored in the values. So: t = (1,'a',None) a,b,c = t. will assign 1 to a, 'a' to b and None to c. Note that this is not syntactical sugar: the compiler does not look whether ...

  2. How does Python's comma operator work during assignment?

    32. Python does not have a "comma operator" as in C. Instead, the comma indicates that a tuple should be constructed. The right-hand side of. a, b = a + b, a. is a tuple with th two items a + b and a. On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed according to the rules you quoted: a will ...

  3. Python's Assignment Operator: Write Robust Assignments

    Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code. ... Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what's known as an iterable unpacking operation.

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

  5. python: comma, = assignment! (beginner

    today I talk about the 1-ary unpacking assignment and an example and why it's useful!- variable unpackings: https://youtu.be/ObWh1AYClI0playlist: https://www...

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

  7. 6. Expressions

    A trailing comma is required only to create a one-item tuple, such as 1,; it is optional in all other cases. A single expression without a trailing comma doesn't create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().) 6.16. Evaluation order¶

  8. Assignments

    Another handy feature of the assignment operator in python is that it supports multiple assignments. If you have a comma separated list of variables on the left hand side of the equal sign, and an equal number of comma separated expressions on the right hand side, python assigns each variable to its corresponding expression: ...

  9. How does Python's comma operator work during assignment?

    Alternatively, the comma operator can also be used to group multiple variables together in a tuple when assigning a single value. For example: a, b = (1, 2) In this example, the tuple (1, 2) is assigned to the variables a and b using the comma operator to separate the variables being assigned the same value. The Comma Operator in Python: An ...

  10. csv

    The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180.The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications.

  11. Unpacking in Python: Beyond Parallel Assignment

    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.

  12. Python program to input a comma separated string

    Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways: Using List comprehension and split() Using map() and split() Method 1: Using List comprehension and split() split() function helps in getting multiple inputs from the user ...

  13. Multiple Assignment Syntax in Python

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

  14. python

    In Python, if we put multiple values/variables separated by commas (with or without parenthesis) like above, that is considered as a tuple. That is the reason when you are trying to print the value of a, b you are getting the output in format of a tuple.

  15. 5 Best Ways to Split a String and Join with a Comma in Python

    Method 4: Using the replace () Method. If your string uses a consistent separator that you wish to replace with a comma, Python's replace () method can directly substitute the old separator with the new one. Here's an example: text = "apple orange banana". comma_separated = text.replace(" ", ",")

  16. 8. Compound statements

    8.4.2. except* clause¶ The except* clause(s) are used for handling ExceptionGroup s. The exception type for matching is interpreted as in the case of except, but in the case of exception groups we can have partial matches when the type matches some of the exceptions in the group.This means that multiple except* clauses can execute, each handling part of the exception group.

  17. Python Split String by Comma

    Python - Split String by Comma. You can split a string in Python with the string formed by the chunks and commas separating them. In this tutorial, we will learn how to split a string by comma , in Python using String.split(). Examples 1. Split given string by comma. In this example, we will take a string with chunks separated by comma ...

  18. variable assignment order in python comma-separated multiple assignment

    Changing variable order in Python comma-separated multiple assignment [duplicate] Essentially I do not understand what order python does variable assignment when you assign multiple of them in the same line. For example: a, b, = [2,3,4,5], [1] a[1:], a, b = b, a[1:], a print("a = ", a) print("b = ", b)

  19. Python

    Method 3 - Custom Split Comma Separated Words Using String split () Method. In this method to achieve the same result is by using the string split () method. we can split the string based on the comma separator, and then strip any whitespace characters from each resulting substring. Python3. test_str = 'geeksforgeeks, is, best, for, geeks'.

  20. python: setting two variable values separated by a comma in python

    Here are a few additional points related to setting variable values separated by commas in Python: Unpacking Iterables: Apart from assigning multiple values to variables, you can also unpack the elements of an iterable (such as a list or tuple) into individual variables using the multiple assignment syntax.

  21. How to split by comma and strip white spaces in Python?

    2. re (as in regular expressions) allows splitting on multiple characters at once: $ string = "blah, lots , of , spaces, here ". $ re.split(', ',string) ['blah', 'lots ', ' of ', ' spaces', 'here '] This doesn't work well for your example string, but works nicely for a comma-space separated list. For your example string, you can combine the re ...