• Google for Education
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Python Lists

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official python.org list docs .)

list of strings 'red' 'blue 'green'

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.

python assignment with list

The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see is with lists. The *for* construct -- for var in list -- is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.

If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as "num", or "name", or "url". Since Python code does not have other syntax to remind you of types, your variable names are a key way for you to keep straight what is going on. (This is a little misleading. As you gain more exposure to python, you'll see references to type hints which allow you to add typing information to your function definitions. Python doesn't use these type hints when it runs your programs. They are used by other programs such as IDEs (integrated development environments) and static analysis tools like linters/type checkers to validate if your functions are called with compatible arguments.)

The *in* construct on its own is an easy way to test if an element appears in a list (or other collection) -- value in collection -- tests if the value is in the collection, returning True/False.

The for/in constructs are very commonly used in Python code and work on data types other than list, so you should just memorize their syntax. You may have habits from other languages where you start manually iterating over a collection, where in Python you should just use for/in.

You can also use for/in to work on a string. The string acts like a list of its chars, so for ch in s: print(ch) prints all the chars in a string.

The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1 -- up to but not including the last number. The combination of the for-loop and the range() function allow you to build a traditional numeric for loop:

There is a variant xrange() which avoids the cost of building the whole list for performance sensitive cases (in Python 3, range() will have the good performance behavior and you can forget about xrange()).

Python also has the standard while-loop, and the *break* and *continue* statements work as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers. Here's a while loop which accesses every 3rd element in a list:

List Methods

Here are some other common list methods.

  • list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
  • list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
  • list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
  • list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
  • list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
  • list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
  • list.reverse() -- reverses the list in place (does not return it)
  • list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

Notice that these are *methods* on a list object, while len() is a function that takes the list (or string or whatever) as an argument.

Common error: note that the above methods do not *return* the modified list, they just modify the original list.

List Build Up

One common pattern is to start a list as the empty list [], then use append() or extend() to add elements to it:

List Slices

Slices work on lists just as with strings, and can also be used to change sub-parts of the list.

Exercise: list1.py

To practice the material in this section, try the problems in list1.py that do not use sorting (in the Basic Exercises ).

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-07-23 UTC.

Python Land

Python List: How To Create, Sort, Append, Remove, And More

The Python list is one of the most used Python data structures, together with dictionaries . The list is not just a list but can also be used as a stack or a queue. In this article, I’ll explain everything you might want to know about Python lists:

  • how to create lists,
  • modify them,
  • how to sort lists,
  • loop over elements of a list with a for-loop or a list comprehension ,
  • how to slice a list,
  • append to Python lists,
  • … and more!

I’ve included lots of working code examples to demonstrate.

Table of Contents

  • 1 How to create a Python list
  • 2 Accessing Python list elements
  • 3 Adding and removing elements
  • 4 How to get List length in Python
  • 5 Counting element occurrence in a list
  • 6 Check if an item is in a list
  • 7 Find the index of an item in a list
  • 8 Loop over list elements
  • 9 Python list to string
  • 10 Sorting Python lists
  • 12 Reversing Python lists
  • 13 Learn more about Python lists

How to create a Python list

Let’s start by creating a list:

Lists contain regular Python objects, separated by commas and surrounded by brackets. The elements in a list can have any data type and can be mixed. You can even create a list of lists. The following lists are all valid:

Using the list() function

Python lists, like all Python data types, are objects. The list class is called ‘list’, and it has a lowercase L. If you want to convert another Python object to a list, you can use the list() function, which is actually the constructor of the list class itself. This function takes one argument: an iterable object.

So you can convert anything iterable into a list. E.g., you can materialize the range function into a list of actual values or convert a Python set or tuple into a list:

Accessing Python list elements

To access an individual list element, you need to know its position. Since computers start counting at 0, the first element is in position 0, and the second element is in position 1, etcetera.

Here are a few examples:

As you can see, you can’t access elements that don’t exist. In this case, Python throws an IndexError exception , with the explanation ‘list index out of range.’ In my article on exceptions and the try and except statements, I’ve written about this subject in more depth in the section on best practices. I recommend you to read it.

Get the last element of a list

If you want to get elements from the end of the list, you can supply a negative value. In this case, we start counting at -1 instead of 0. E.g. to get the last element of a list, you can do this:

Accessing nested list elements

Accessing nested list elements is not that much different. When you access an element that is a list, that list is returned. So, to request an element in that list, you need to use a couple of brackets again:

Adding and removing elements

Let’s see how we can add and remove data. There are several ways to remove data from a list. What you use depends on the situation. I’ll describe and demonstrate them all in this section.

Append to a Python list

List objects have several useful built-in methods, one of which is the append method. When calling append on a list, we append an object to the end of the list:

Combine or merge two lists

Another way of adding elements is adding all the elements from one list to the other. There are two ways to combine lists:

  • ‘Add’ them together with the + operator.
  • Add all elements of one list to the other with the extend method.

Here’s how you can add two lists together. The result is a new, third list:

The original lists are kept intact. The alternative is to extend one list with another using the extend method:

While l1 got extended with the elements of l2, l2 stayed the same. Extend appended all values from l2 to l1 and kept l2 as-is.

Pop items from a list

The pop() method removes and returns the last item by default unless you give it an index argument.

Here are a couple of examples that demonstrate both the default behavior and the behavior when given an index:

If you’re familiar with the concept of a stack , you can now build one using only the append and pop methods on a list!

Using del to delete items

There are multiple ways to delete or remove items from a list. While pop() returns the item that is deleted from the list, del removes it without returning anything. In fact, you can delete any object, including the entire list, using del:

del is not list-specific; it can delete any object in Python and does so recursively as well. Deleting things lets Python know it can free up the memory that was being used by the deleted object(s). For small programs, you don’t have to bother. However, if you load a lot of data in memory, it can be beneficial to explicitly delete the data you don’t need anymore.

Remove specific values from a Python list

If you want to remove a specific value from the list, use the remove() method. This method will remove the first occurrence of the given object in a list. Let’s demonstrate this by remove the number two from my_list :

As you can see, repeated calls to remove will remove additional twos until none are left, in which case Python throws a ValueError exception .

Remove or clear all items from a Python list

To remove all items from a list, use the clear() method:

Remove duplicates from a list

There is no particular function or method to remove duplicates from a list, but there are multiple tricks that we can use to do so anyway. The simplest, in my opinion, is using a Python set . Sets are collections of objects, like lists, but can only contain one of each element. More formally, sets are unordered collections of distinct objects.

By converting the list to a set and then back to a list again, we’ve effectively removed all duplicates:

I’ve demonstrated this quite explicitly, but you usually want to use this more compact version:

Since sets are very similar to lists, you may not have to convert them back into a list. If the set offers what you need, use it instead to prevent a double conversion, making your program a little bit faster and more efficient.

Replace items in a list

To replace list items, we assign a new value to a given list index, like so:

How to get List length in Python

In Python, we use the len function to get the length of objects. This is true for lists as well:

If you’re familiar with other programming languages, like Java, you might wonder why Python has a function for this. After all, it could have been one of the built-in methods of a list too, like my_list.len() . This is because, in other languages, this often results in various ways to get an object’s length. E.g., some will call this function len , others will call it length, and yet someone else won’t even implement the function but simply offer a public member variable. And this is exactly the reason why Python chose to standardize the naming of such a common operation!

Counting element occurrence in a list

Don’t confuse the count function with getting the list length; it’s totally different. The built-in count function counts occurrences of a particular value inside that list. Here’s an example:

Since the number 1 occurs three times in the list, my_list.count(1) returns 3.

Check if an item is in a list

To check if an item is in a list, use the following syntax:

Find the index of an item in a list

We can find where an item is inside a list with the index method. For example, in the following list, the 4 is located at position 3 (remember that we start counting at zero):

The index method takes two optional parameters: start and stop. With these, we can continue looking for more of the same values. We don’t need to supply an end value if we provide a start value. Now, let’s find both 4’s in the list below:

If you want to do more advanced filtering of lists, you should read my article on list comprehensions .

Loop over list elements

A list is iterable , so we can use a for-loop over the elements of a list just like we can with any other iterable with the ‘for <element> in <iterable>’ syntax:

Python list to string

In Python, you can convert most objects to a string with the str function:

If you’re interested, str is actually the Python string ‘s base class and calling str() constructs a new str object by calling the constructor of the str class. This constructor inspects the provided object and looks for a special method (also called dunder method) called __str__ . If it is present, this method is called. There’s nothing more to it.

If you create your own classes and objects , you can implement the __str__ function yourself to offer a printable version of your objects.

Sorting Python lists

To sort a Python list, we have two options:

  • Use the built-in sort method of the list itself.
  • Use Python’s built-in sorted() function.

Option one, the built-in method, offers an in-place sort. In other words, this function does not return anything. Instead, it modifies the list itself.

Option two returns a new list, leaving the original intact. Which one you use depends on the situation you’re in.

In-place list sort in ascending order

Let’s start with the simplest use-case: sorting in ascending order:

In-place list sort in descending order

We can call the sort method with a reverse parameter. If this is set to True, sort reverses the order:

Using sorted()

The following example demonstrates how to sort lists in ascending order, returning a new list with the result:

As you can see from the last statement, the original list is unchanged. Let’s do that again, but now in descending order:

Unsortable lists

We can not sort all lists since Python can not compare all types with each other. For example, we can sort a list of numbers, like integers and floats, because they have a defined order. We can sort a list of strings as well since Python is able to compare strings too.

However, lists can contain any type of object, and we can’t compare completely different objects, like numbers and strings, to each other. In such cases, Python throws a TypeError :

Although the error might look cryptic, it’s only logical when you know what’s going on. To sort a list, Python needs to compare the objects to each other. So in its sorting algorithm, at some point, it checks if ‘a’ < 1, hence the error: '<' not supported between instances of 'str' and 'int' .

Sometimes you need to get parts of a list. Python has a powerful syntax to do so, called slicing, and it makes working with lists much easier than other programming languages. Slicing works on Python lists and all other sequence types, like strings , tuples , and ranges .

The slicing syntax is as follows:

my_list[start:stop:step]

A couple of notes:

  • start is the first element position to include
  • stop is exclusive, meaning that the element at position stop won’t be included.
  • step is the step size. more on this later.
  • start , stop , and step are all optional.
  • Negative values can be used too.

To explain how slicing works, it’s best to just look at examples, and try for yourself, so that’s what we’ll do:

The step value

The step value in a slice is one by default. A step size of one means all elements are considered for the slice. If you increase the step size, you can step over elements. E.g., a step size of two means on each step, one element is skipped over. Let’s try this:

Going backward

Like with list indexing, we can also supply negative numbers with slicing. Here’s a little ASCII art to show you how counting backward in a list works:

Just remember that you need to set a negative step size to go backward:

Reversing Python lists

There are three methods you can use to reverse a list in Python:

  • An in-place reverse, using the built-in reverse method that every list has natively
  • Using list slicing with a negative step size results in a new list
  • Create a reverse iterator , with the reversed() function

In the following code crumb, I demonstrate all three. They are explained in detail in the following sections:

Using the built-in reverse method

The list.reverse() method does an in-place reverse, meaning it reorders the list. In other words, the method does not return a new list object, with a reversed order. Here’s how to use reverse() :

Reverse a list with list slicing

Although you can reverse a list with the list.reverse() method that every list has, you can do it with list slicing too, using a negative step size of -1. The difference is that list slicing results in a new, second list. It keeps the original list intact:

Creating a reverse iterator

Finally, you can use the reversed() built-in function, which creates an iterator that returns all elements of the given iterable (our list) in reverse. This method is quite cheap in terms of CPU and memory usage. All it needs to do is walk backward over the iterable object. It doesn’t need to move around data, and it doesn’t need to reserve extra memory for a second list. So if you need to iterate over a (large) list in reverse, this should be your choice.

Here’s how you can use this function. Keep in mind that you can only use the iterator once but that it’s cheap to make a new one:

Learn more about Python lists

Because there’s a lot to tell about list comprehensions, I created a dedicated article for the topic. A Python list comprehension is a language construct that we use to efficiently create a list based on an existing list (without using for-loops ).

Some other resources you might like:

  • The official Python docs about lists.
  • If you are interested in the internals, lists are often implemented internally as a linked list .
  • Python also has arrays , which are very similar and the term will be familiar to people coming from other programming languages. They are more efficient at storing data, but they can only store one type of data.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Related articles

  • Python List Comprehension: Tutorial With Examples
  • Python For Loop and While Loop
  • Python Tuple: How to Create, Use, and Convert
  • JSON in Python: How To Read, Write, and Parse

Python Programming

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • Each exercise has 10-20 Questions.
  • The solution is provided for every question.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve .

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics : Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics : print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics : If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics : Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics : Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics : Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics : random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question :

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string

Exercise 2: Read text file into a variable and replace all newlines with space

Given : Assume you have a following text file (sample.txt).

Expected Output :

  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).

Steps to solve this question : -

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Display final string

Exercise 3: Remove items from a list while iterating

Description :

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Expected Output : -

  • Get the list's size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

Solution 2: Using for loop and range()

Exercise 4: Reverse Dictionary mapping

Exercise 5: display all duplicate items from a list.

  • Use the counter() method of the collection module.
  • Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1 : - Using collections.Counter()

Solution 2 : -

Exercise 6: Filter dictionary to contain keys present in the given list

Exercise 7: print the following number pattern.

Refer to Print patterns in Python to solve this question.

  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop

Exercise 8: Create an inner function

Question description : -

  • Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word 'developer' to it.

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

Exercise 10: Access the nested key increment from the following dictionary

Under Exercises: -

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on:  December 8, 2021 | 52 Comments

Python Date and Time Exercise with Solutions

Updated on:  December 8, 2021 | 10 Comments

Python Dictionary Exercise with Solutions

Updated on:  May 6, 2023 | 56 Comments

Python Tuple Exercise with Solutions

Updated on:  December 8, 2021 | 96 Comments

Python Set Exercise with Solutions

Updated on:  October 20, 2022 | 28 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on:  September 3, 2024 | 301 Comments

Updated on:  August 2, 2022 | 155 Comments

Updated on:  September 6, 2021 | 109 Comments

Python List Exercise with Solutions

Updated on:  December 8, 2021 | 203 Comments

Updated on:  December 8, 2021 | 7 Comments

Python Data Structure Exercise for Beginners

Updated on:  December 8, 2021 | 116 Comments

Python String Exercise with Solutions

Updated on:  October 6, 2021 | 221 Comments

Updated on:  March 9, 2021 | 24 Comments

Updated on:  March 9, 2021 | 52 Comments

Updated on:  July 20, 2021 | 29 Comments

Python Basic Exercise for Beginners

Updated on:  August 29, 2024 | 498 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Updated on:  May 17, 2021 | 23 Comments

Python random Data generation Exercise

Updated on:  December 8, 2021 | 13 Comments

Python Database Programming Exercise

Updated on:  March 9, 2021 | 17 Comments

  • Online Python Code Editor

Updated on:  June 1, 2022 |

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Assignment Operators in Python

The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .

Operators

=

Assign the value of the right side of the expression to the left side operandc = a + b 


+=

Add right side operand with left side operand and then assign the result to left operanda += b   

-=

Subtract right side operand from left side operand and then assign the result to left operanda -= b  


*=

Multiply right operand with left operand and then assign the result to the left operanda *= b     


/=

Divide left operand with right operand and then assign the result to the left operanda /= b


%=

Divides the left operand with the right operand and then assign the remainder to the left operanda %= b  


//=

Divide left operand with right operand and then assign the value(floor) to left operanda //= b   


**=

Calculate exponent(raise power) value using operands and then assign the result to left operanda **= b     


&=

Performs Bitwise AND on operands and assign the result to left operanda &= b   


|=

Performs Bitwise OR on operands and assign the value to left operanda |= b    


^=

Performs Bitwise XOR on operands and assign the value to left operanda ^= b    


>>=

Performs Bitwise right shift on operands and assign the result to left operanda >>= b     


<<=

Performs Bitwise left shift on operands and assign the result to left operanda <<= b 


:=

Assign a value to a variable within an expression

a := exp

Here are the Assignment Operators in Python with examples.

Assignment Operator

Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.

S ubtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.

M ultiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.

D ivision Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.

M odulus Assignment Operator

The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.

F loor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.

Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.

Bitwise XOR Assignment Operator 

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.

Walrus Operator

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.

Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.

Assignment Operators in Python – FAQs

What are assignment operators in python.

Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment. The basic assignment operator is = , which simply assigns the value of the right-hand operand to the left-hand operand. Other common assignment operators include += , -= , *= , /= , %= , and more, which perform an operation on the variable and then assign the result back to the variable.

What is the := Operator in Python?

The := operator, introduced in Python 3.8, is known as the “walrus operator”. It is an assignment expression, which means that it assigns values to variables as part of a larger expression. Its main benefit is that it allows you to assign values to variables within expressions, including within conditions of loops and if statements, thereby reducing the need for additional lines of code. Here’s an example: # Example of using the walrus operator in a while loop while (n := int(input("Enter a number (0 to stop): "))) != 0: print(f"You entered: {n}") This loop continues to prompt the user for input and immediately uses that input in both the condition check and the loop body.

What is the Assignment Operator in Structure?

In programming languages that use structures (like C or C++), the assignment operator = is used to copy values from one structure variable to another. Each member of the structure is copied from the source structure to the destination structure. Python, however, does not have a built-in concept of ‘structures’ as in C or C++; instead, similar functionality is achieved through classes or dictionaries.

What is the Assignment Operator in Python Dictionary?

In Python dictionaries, the assignment operator = is used to assign a new key-value pair to the dictionary or update the value of an existing key. Here’s how you might use it: my_dict = {} # Create an empty dictionary my_dict['key1'] = 'value1' # Assign a new key-value pair my_dict['key1'] = 'updated value' # Update the value of an existing key print(my_dict) # Output: {'key1': 'updated value'}

What is += and -= in Python?

The += and -= operators in Python are compound assignment operators. += adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. Conversely, -= subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand. Here are examples of both: # Example of using += a = 5 a += 3 # Equivalent to a = a + 3 print(a) # Output: 8 # Example of using -= b = 10 b -= 4 # Equivalent to b = b - 4 print(b) # Output: 6 These operators make code more concise and are commonly used in loops and iterative data processing.

author

Please Login to comment...

Similar reads.

  • Python-Operators
  • How to Strikethrough on Discord
  • Discord Launches End-To-End Encryption For Audio & Video Chats
  • iPadOS 18 is Now Available: Complete Features and How to Install
  • Microsoft’s Latest 365 Copilot Updates: Enhanced AI Tools for Excel, PowerPoint, and Teams
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics

Python List

Python Tuple

  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python List pop()

Python List extend()

Python List insert()

  • Python List append()
  • Python List index()
  • Python List remove()

There are many built-in types in Python that allow us to group and store multiple items. Python lists are the most versatile among them.

For example, we can use a Python list to store a playlist of songs so that we can easily add, remove, and update songs as needed.

  • Create a Python List

We create a list by placing elements inside square brackets [] , separated by commas. For example,

Here, the ages list has three items.

We can store data of different data types in a Python list. For example,

We can use the built-in list() function to convert other iterables (strings, dictionaries, tuples, etc.) to a list.

List Characteristics

  • Ordered - They maintain the order of elements.
  • Mutable - Items can be changed after creation.
  • Allow duplicates - They can contain duplicate values.
  • Access List Elements

Each element in a list is associated with a number, known as an index .

The index of first item is 0 , the index of second item is 1 , and so on.

Index of Python List Elements

We use these index numbers to access list items. For example,

Access List Elements Using Index

More on Accessing List Elements

Python also supports negative indexing. The index of the last element is -1 , the second-last element is -2 , and so on.

Python Negative Indexing

Negative indexing makes it easy to access list items from last.

Let's see an example,

In Python, it is possible to access a section of items from the list using the slicing operator : . For example,

To learn more about slicing, visit Python program to slice lists .

Note : If the specified index does not exist in a list, Python throws the IndexError exception.

  • Add Elements to a Python List

We use the append() method to add an element to the end of a Python list. For example,

The insert() method adds an element at the specified index. For example,

We use the extend() method to add elements to a list from other iterables. For example,

  • Change List Items

We can change the items of a list by assigning new values using the = operator. For example,

Here, we have replaced the element at index 2: 'Green' with 'Blue' .

  • Remove an Item From a List

We can remove an item from a list using the remove() method. For example,

The del statement removes one or more items from a list. For example,

Note : We can also use the del statement to delete the entire list. For example,

  • Python List Length

We can use the built-in len() function to find the number of elements in a list. For example,

  • Iterating Through a List

We can use a for loop to iterate over the elements of a list. For example,

  • Python List Methods

Python has many useful list methods that make it really easy to work with lists.

Method Description
Adds an item to the end of the list
Adds items of lists and other iterables to the end of the list
Inserts an item at the specified index
Removes the specified value from the list
Returns and removes item present at the given index
Removes all items from the list
Returns the index of the first matched item
Returns the count of the specified item in the list
Sorts the list in ascending/descending order
Reverses the item of the list
Returns the shallow copy of the list

More on Python Lists

List Comprehension is a concise and elegant way to create a list. For example,

To learn more, visit Python List Comprehension .

We use the in keyword to check if an item exists in the list. For example,

  • orange is not present in fruits , so, 'orange' in fruits evaluates to False .
  • cherry is present in fruits , so, 'cherry' in fruits evaluates to True .

Note: Lists are similar to arrays (or dynamic arrays) in other programming languages. When people refer to arrays in Python, they often mean lists, even though there is a numeric array type in Python.

  • Python list()

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of Python list to the test! Can you solve the following challenge?

Write a function to find the largest number in a list.

  • For input [1, 2, 9, 4, 5] , the return value should be 9 .

Video: Python Lists and Tuples

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Library

Python Tutorial

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

7. Simple statements ¶

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

7.1. Expression statements ¶

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

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

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

7.2. Assignment statements ¶

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

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

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

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

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

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

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

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

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

If the target is an identifier (name):

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

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

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

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

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

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

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

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

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

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

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

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

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

The specification for the *target feature.

7.2.1. Augmented assignment statements ¶

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

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

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

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

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

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

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

7.2.2. Annotated assignment statements ¶

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

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

The assignment target is considered “simple” if it consists of a single name that is not enclosed in parentheses. For simple assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

If the assignment target is not simple (an attribute, subscript node, or parenthesized name), the annotation is evaluated if in class or module scope, but not stored.

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

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

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

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

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

7.3. The assert statement ¶

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

The simple form, assert expression , is equivalent to

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

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

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

7.4. The pass statement ¶

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

7.5. The del statement ¶

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

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

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

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

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

7.6. The return statement ¶

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

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

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

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

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

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

7.7. The yield statement ¶

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

are equivalent to the yield expression statements

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

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

7.8. The raise statement ¶

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

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

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

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

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

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

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

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

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

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

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

7.9. The break statement ¶

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

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

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

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

7.10. The continue statement ¶

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

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

7.11. The import statement ¶

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

find a module, loading and initializing it if necessary

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

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

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

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

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

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

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

The from form uses a slightly more complex process:

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

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

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

if the attribute is not found, ImportError is raised.

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

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

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

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

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

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

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

7.11.1. Future statements ¶

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

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

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

the module docstring (if any),

blank lines, and

other future statements.

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

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

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

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

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

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

Note that there is nothing special about the statement:

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

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

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

The original proposal for the __future__ mechanism.

7.12. The global statement ¶

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

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

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

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

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

7.13. The nonlocal statement ¶

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

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

The specification for the nonlocal statement.

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

7.14. The type statement ¶

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

For example, the following statement creates a type alias:

This code is roughly equivalent to:

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

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

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

type is a soft keyword .

Added in version 3.12.

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

Table of Contents

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

Previous topic

6. Expressions

8. Compound statements

  • Report a Bug
  • Show Source

Python Tutorial

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

Assignment operators are used to assign values to variables:

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

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

Dict built-in get/set methods for nested keys

apparently, there is no built-in dict method (let’s call it .nestkey ) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures,

e.g., dic_1.nestkey(list_of_keys_A) = value instead of manually doing dic_1["key_1"]["subkey_2"]["subsubkey_3"] = value .

this is not to be confused with level-1 assignment: dic_1["key_1"] = value_1, dic_2["key_2"] = value_2, ...

i know it’s generally good practice to avoid nested structures, but when necessary, dynamic addressing is powerful,

for this purpose, i suggest implement a set/get couple of built-in dict methods, setnest and getnest respectively,

I think the Benedict library does this: python-benedict · PyPI

It has dynamic keyattr functionality which seems like what you’re looking for.

See also glom :

By the way, this thread isn’t in the right category. I believe it should be moved to Ideas .

Lists vs Tuples in Python

Lists vs Tuples in Python

Table of Contents

Creating Lists in Python

Creating tuples in python, lists and tuples are ordered sequences, lists and tuples can contain arbitrary objects, lists and tuples can be indexed and sliced, lists and tuples can be nested, lists are mutable, tuples are immutable, lists have mutator methods, tuples don’t, using operators and built-in functions with lists and tuples, packing and unpacking lists and tuples, using lists vs tuples in python.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Lists and Tuples in Python

In Python, lists and tuples are versatile and useful data types that allow you to store data in a sequence. You’ll find them in virtually every nontrivial Python program. Learning about them is a core skill for you as a Python developer.

In this tutorial, you’ll:

  • Get to know lists and tuples
  • Explore the core characteristics of lists and tuples
  • Learn how to define and manipulate lists and tuples
  • Decide when to use lists or tuples in your code

To get the most out of this tutorial, you should know the basics of Python programming, including how to define variables.

Get Your Code: Click here to download the free sample code that shows you how to work with lists and tuples in Python.

Take the Quiz: Test your knowledge with our interactive “Lists vs Tuples in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Challenge yourself with this quiz to evaluate and deepen your understanding of Python lists and tuples. You'll explore key concepts, such as how to create, access, and manipulate these data types, while also learning best practices for using them efficiently in your code.

Getting Started With Python Lists and Tuples

In Python, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. To define a list, you typically enclose a comma-separated sequence of objects in square brackets ( [] ), as shown below:

In this code snippet, you define a list of colors using string objects separated by commas and enclose them in square brackets.

Similarly, tuples are also collections of arbitrary objects. To define a tuple, you’ll enclose a comma-separated sequence of objects in parentheses ( () ), as shown below:

In this example, you define a tuple with data for a given person, including their name, age, job, and base country.

Up to this point, it may seem that lists and tuples are mostly the same. However, there’s an important difference:

Feature List Tuple
Is an ordered sequence
Can contain arbitrary objects
Can be indexed and sliced
Can be nested
Is mutable

Both lists and tuples are sequence data types, which means they can contain objects arranged in order. You can access those objects using an integer index that represents their position in the sequence.

Even though both data types can contain arbitrary and heterogeneous objects, you’ll commonly use lists to store homogeneous objects and tuples to store heterogeneous objects.

Note: In this tutorial, you’ll see the terms homogeneous and heterogeneous used to express the following ideas:

  • Homogeneous : Objects of the same data type or the same semantic meaning, like a series of animals, fruits, colors, and so on.
  • Heterogeneous : Objects of different data types or different semantic meanings, like the attributes of a car: model, color, make, year, fuel type, and so on.

You can perform indexing and slicing operations on both lists and tuples. You can also have nested lists and nested tuples or a combination of them, like a list of tuples.

The most notable difference between lists and tuples is that lists are mutable, while tuples are immutable. This feature distinguishes them and drives their specific use cases.

Essentially, a list doesn’t have a fixed length since it’s mutable. Therefore, it’s natural to use homogeneous elements to have some structure in the list. A tuple, on the other hand, has a fixed length so the position of elements can have meaning, supporting heterogeneous data.

In many situations, you’ll define a list object using a literal . A list literal is a comma-separated sequence of objects enclosed in square brackets:

In this example, you create a list of countries represented by string objects. Because lists are ordered sequences, the values retain the insertion order.

Note: To learn more about the list data type, check out the Python’s list Data Type: A Deep Dive With Examples tutorial.

Alternatively, you can create new lists using the list() constructor :

In this example, you use the list() constructor to define a list of digits using a range object. In general, list() can convert any iterable to a list.

You can also create new list objects using list comprehensions . For example, the following comprehension builds a list of even digits:

List comprehensions are powerful tools for creating lists in Python. You’ll often find them in Python code that runs transformations over sequences of data.

Finally, to create an empty list, you can use either an empty pair of square brackets or the list() constructor without arguments:

The first approach is arguably the most efficient and most commonly used. However, the second approach can be more explicit and readable in some situations.

Similar to lists, you’ll often create new tuples using literals. Here’s a short example showing a tuple definition:

In this example, you create a tuple containing the parameters for a database connection. The data includes the server name, port, timeout, and database name.

Note: To dive deeper into the tuple data type, check out the Python’s tuple Data Type: A Deep Dive With Examples tutorial.

Strictly speaking, to define a tuple, you don’t need the parentheses. The comma-separated sequence will be enough:

In practice, you can define tuples without using a pair of parentheses. However, using the parentheses is a common practice because it improves the readability of your code.

Because the parentheses are optional, to define a single-item tuple, you need to use a comma:

In the first example, you create a tuple containing a single value by appending a comma after the value. In the second example, you use the parentheses without the comma. In this case, you create an integer value instead of a tuple.

You can also create new tuples using the tuple() constructor:

In this example, you create a list of digits using tuple() . This way of creating tuples can be helpful when you’re working with iterators and need to convert them into tuples.

Finally, to create empty tuples, you can use a pair of parentheses or call tuple() without arguments:

The first approach is a common way to create empty tuples. However, using tuple() can be more explicit and readable.

Exploring Core Features of Lists and Tuples

Now that you know the basics of creating lists and tuples in Python, you’re ready to explore their most relevant features and characteristics. In the following section, you’ll dive into these features and learn how they can impact the use cases of lists and tuples in your Python code.

List and tuples are ordered sequences of objects. The order in which you insert the objects when you create a list or tuple is an innate characteristic. This order remains the same for that list or tuple’s lifetime:

In these examples, you can confirm that the order of items in lists and tuples is the same order you define when creating the list or tuple.

Lists and tuples can contain any Python objects. The elements of a list or tuple can all be the same type:

In these examples, you create a list of integer numbers and then a tuple of similar objects. In both cases, the contained objects have the same data type. So, they’re homogeneous.

The elements of a list or tuple can also be of heterogeneous data types:

Here, your list and tuple contain objects of different types, including strings, integers, Booleans, and floats. So, your list and tuple are heterogeneous.

Note: Even though lists and tuples can contain heterogeneous or homogeneous objects, the common practice is to use lists for homogeneous objects and tuples for heterogeneous objects.

Lists and tuples can even contain objects like functions, classes, and modules:

In these examples, the list and the tuple contain a class, built-in function , custom function , and module objects.

Lists and tuples can contain any number of objects, from zero to as many as your computer’s memory allows. In the following code, you have a list and tuple built out of a range with a million numbers:

These two lines of code will take some time to run and populate your screen with many, many numbers.

Finally, objects in a list or tuple don’t need to be unique. A given object can appear multiple times:

Lists and tuples can contain duplicated values like "bark" in the above examples.

You can access individual elements in a list or tuple using the item’s index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based, as it is with strings.

Consider the following list:

The indices for the elements in words are shown below:

Diagram of a Python list

Here’s the Python code to access individual elements of words :

The first element in the list has an index of 0 . The second element has an index of 1 , and so on. Virtually everything about indexing works the same for tuples.

You can also use a negative index, in which case the count starts from the end of the list:

Diagram of a Python list

Index -1 corresponds to the last element in the list, while the first element is -len(words) , as shown below:

Slicing also works with lists and tuples. For example, the expression words[m:n] returns the portion of words from index m to, but not including, index n :

Other features of slicing work for lists as well. For example, you can use both positive and negative indices:

Omitting the first index starts the slice at the beginning of the list or tuple. Omitting the second index extends the slice to the end of the list or tuple:

You can specify a stride—either positive or negative:

The slicing operator ( [:] ) works for both lists and tuples. You can check it out by turning words into a tuple and running the same slicing operations on it.

You’ve seen that an element in a list or tuple can be of any type. This means that they can contain other lists or tuples. For example, a list can contain sublists, which can contain other sublists, and so on, to arbitrary depth.

Consider the following example:

The internal structure of this list is represented in the diagram below:

Nested lists diagram

In this diagram, x[0] , x[2] , and x[4] are strings, each one character long:

However, x[1] and x[3] are sublists or nested lists:

To access the items in a sublist, append an additional index:

Here, x[1][1] is yet another sublist, so adding one more index accesses its elements:

There’s no limit to the depth you can nest lists this way. However, deeply nested lists or tuples can be hard to decipher in an indexing or slicing context.

The built-in list class provides a mutable data type. Being mutable means that once you create a list object, you can add, delete, shift, and move elements around at will. Python provides many ways to modify lists, as you’ll learn in a moment. Unlike lists, tuples are immutable , meaning that you can’t change a tuple once it has been created.

Note: To learn more about mutability and immutability in Python, check out the Python’s Mutable vs Immutable Types: What’s the Difference? tutorial.

You can replace or update a value in a list by indexing it on the left side of an assignment statement:

In this example, you create a list of letters where some letters are in uppercase while others are in lowercase. You use an assignment to turn the lowercase letters into uppercase letters.

Now, because tuples are immutable, you can’t do with a tuple what you did in the above example with a list:

If you try to update the value of a tuple element, you get a TypeError exception because tuples are immutable, and this type of operation isn’t allowed for them.

You can also use the del statement to delete individual items from a list. However, that operation won’t work on tuples:

You can remove individual elements from lists using the del statement because lists are mutable, but this won’t work with tuples because they’re immutable.

Note: To learn more about the del statement, check out the Python’s del : Remove References From Scopes and Containers tutorial.

What if you want to change several elements in a list at once? Python allows this operation with a slice assignment , which has the following syntax:

Think of an iterable as a container of multiple values like a list or tuple. This assignment replaces the specified slice of a_list with the content of <iterable> :

In this example, you replace the 0 values with the corresponding consecutive numbers using a slice assignment.

It’s important to note that the number of elements to insert doesn’t need to be equal to the number of elements in the slice. Python grows or shrinks the list as needed. For example, you can insert multiple elements in place of a single element:

In this example, you replace the 7 with a list of values from 4 to 7 . Note how Python automatically grows the list for you.

You can also insert elements into a list without removing anything. To do this, you can specify a slice of the form [n:n] at the desired index:

In this example, you insert the desired values at index 3 . Because you’re using an empty slice, Python doesn’t replace any of the existing values. Instead, it makes space for the new values as needed.

You can’t do slice assignment on tuple objects:

Because tuples are immutable, they don’t support slice assignment. If you try to do it, then you get a TypeError exception.

Python lists have several methods that you can use to modify the underlying list. These methods aren’t available for tuples because tuples are immutable, so you can’t change them in place.

In this section, you’ll explore the mutator methods available in Python list objects. These methods are handy in many situations, so they’re great tools for you as a Python developer.

.append(obj)

The .append(obj) method appends an object to the end of a list as a single item:

In this example, you append the letter "c" at the end of a using the .append() method, which modifies the list in place.

Note: List mutator methods modify the target list in place . They don’t return a new list:

In this code, you grab the return value of .append() in x . Using the print() function, you can uncover that the value is None instead of a new list object. While this behavior is deliberate to make it clear that the method mutates the object in place, it can be a common source of confusion when you’re starting to learn Python.

If you use an iterable as an argument to .append() , then that iterable is added as a single object:

This call to .append() adds the input list of letters as it is instead of appending three individual letters at the end of a . Therefore, the final list has three elements—the two initial strings and one list object. This may not be what you intended if you wanted to grow the list with the contents of the iterable.

.extend(iterable)

The .extend() method also adds items to the end of a list. However, the argument is expected to be an iterable like another list. The items in the input iterable are added as individual values:

The .extend() method behaves like the concatenation operator ( + ). More precisely, since it modifies the list in place, it behaves like the augmented concatenation operator ( += ). Here’s an example:

The augmented concatenation operator produces the same result as .extend() , adding individual items at the end of the target list.

.insert(index, obj)

The .insert() method inserts the input object into the target list at the position specified by index . Following the method call, a[<index>] is <obj> , and the remaining list elements are pushed to the right:

In this example, you insert the letter "b" between "a" and "c" using .insert() . Note that just like .append() , the .insert() method inserts the input object as a single element in the target list.

.remove(obj)

The .remove() method removes the input object from a list. If obj isn’t in the target list, then you get a ValueError exception:

With .remove() , you can delete specific objects from a given list. Note that this method removes only one instance of the input object. If the object is duplicated, then only its first instance will be deleted.

.pop([index=-1])

The .pop() method also allows you to remove items from a list. It differs from .remove() in two aspects:

  • It takes the index of the object to remove rather than the object itself.
  • It returns the value of the removed object.

Calling .pop() without arguments removes and returns the last item in the list:

If you specify the optional index argument, then the item at that index is removed and returned. Note that index can be negative too:

The index argument defaults to -1 , so a.pop(-1) is equivalent to a.pop() .

Several Python operators and built-in functions also work with lists and tuples. For example, the in and not in operators allow you to run membership tests on lists:

The in operator returns True if the target object is in the list and False otherwise. The not in operator produces the opposite result.

The concatenation ( + ) and repetition ( * ) operators also work with lists and tuples:

You can also use the built-in len() , min() , max() , and sum() functions with lists and tuples:

In this example, the len() function returns the number of values in the list. The min() and max() functions return the minimum and maximum values in the list, respectively. The sum() function returns the sum of the values in the input list.

Finally, it’s important to note that all these functions work the same with tuples. So, instead of using them with list objects, you can also use tuple objects.

A tuple literal can contain several items that you typically assign to a single variable or name:

When this occurs, it’s as though the items in the tuple have been packed into the object, as shown in the diagram below:

tuple packing

If the packed objects are assigned to a tuple of names, then the individual objects are unpacked as shown in the diagram below, where you use a tuple of s* variables:

tuple unpacking

Here’s how this unpacking works in Python code:

Note how each variable receives a single value from the unpacked tuple. When you’re unpacking a tuple, the number of variables on the left must match the number of values in the tuple. Otherwise, you get a ValueError exception:

In the first example, the number of variables is less than the items in the tuple, and the error message says that there are too many values to unpack. In the second example, the number of variables exceeds the number of items in the tuple. This time, the error message says that there aren’t enough values to unpack.

You can combine packing and unpacking in one statement to run a parallel assignment:

Again, the number of elements in the tuple on the left of the assignment must equal the number on the right. Otherwise, you get an error.

Tuple assignment allows for a curious bit of idiomatic Python. Sometimes, when programming, you have two variables whose values you need to swap. In most programming languages, it’s necessary to store one of the values in a temporary variable while the swap occurs.

Consider the following example that compares swapping with a temporary variable and unpacking:

Using a temporary variable to swap values can be annoying, so it’s great that you can do it with a single unpacking operation in Python. This feature also improves your code’s readability, making it more explicit.

Everything you’ve learned so far about lists and tuples can help you decide when to use a list or a tuple in your code. Here’s a summary of when it would be appropriate to use a list instead of a tuple:

  • Mutable collections : When you need to add, remove, or change elements in the collection.
  • Dynamic size : When the collection’s size might change during the code’s execution.
  • Homogeneous data : When you need to store data of a homogeneous type or when the data represents a homogeneous concept.

Similarly, it’s appropriate to use a tuple rather than a list in the following situations:

  • Immutable collections : When you have a fixed collection of items that shouldn’t change, such as coordinates (x, y, z), RGB color values, or other groupings of related values.
  • Fixed size : When the collection’s size won’t change during the code’s execution.
  • Heterogeneous data : When you need to store data of a heterogeneous type or when the data represents a heterogeneous concept.
  • Function’s return values : When a function returns multiple values, you’ll typically use a tuple to pack these values together.

Finally, tuples can be more memory-efficient than lists, especially for large collections where immutability is acceptable or preferred. Similarly, if the integrity of the data is important and should be preserved throughout the program, tuples ensure and communicate that the data must remain unchanged.

Now you know the basic features of Python lists and tuples and understand how to manipulate them in your code. You’ll use these two data types extensively in your Python programming journey.

In this tutorial, you’ve:

  • Learned about the built-in lists and tuples data types in Python
  • Explored the core features of lists and tuples
  • Discovered how to define and manipulate lists and tuples
  • Learned when to use lists or tuples in your code

With this knowledge, you can now decide when it’s appropriate to use a list or tuple in your Python code. You also have the essential skills to create and manipulate lists and tuples in Python.

🐍 Python Tricks 💌

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

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

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

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

Aldren Santos

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

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

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

What Do You Think?

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

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

Keep Learning

Related Topics: basics python

Recommended Video Course: Lists and Tuples in Python

Related Tutorials:

  • Dictionaries in Python
  • Python Classes: The Power of Object-Oriented Programming
  • Sets in Python
  • Using Python's pip to Manage Your Projects' Dependencies
  • Python's list Data Type: A Deep Dive With Examples

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

Already have an account? Sign-In

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

Lists vs Tuples in Python (Sample Code)

🔒 No spam. We take your privacy seriously.

python assignment with list

Cubs activate RHP Hayden Wesneski, designate RHP Shawn Armstrong for assignment

CHICAGO – The Chicago Cubs today activated right-handed pitcher Hayden Wesneski from the 15-day injured list and designated right-handed pitcher Shawn Armstrong for assignment.

Wesneski, 26, was placed on the injured list July 20 with a right forearm strain. In 25 appearances for the Cubs this season – seven starts – he is 3-6 with a 3.94 ERA (27 ER/61.2 IP). He made three rehab outings with Triple-A Iowa, keeping the opponent off the board in two of them.

The Houston, Tex., native, is 9-13 with a 3.96 ERA (81 ER/184.0 IP) and 174 strikeouts, compared to 60 walks, in 65 career major league games, all but 22 of which came in relief. He was acquired by the Cubs in exchange for pitcher Scott Effross at the 2022 trade deadline.

Armstrong, 34, made eight relief appearances for the Cubs, going 0-1 with a 4.91 ERA (4 ER/7.1 IP).

The Cubs play the Washington Nationals today at 1:20 p.m. CT at Wrigley Field in a game that can be seen on Marquee Sports Network and heard on 670 The Score and in Spanish on WRTO 1200.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Assign multiple values of a list

I am curious to know if there is a "pythonic" way to assign the values in a list to elements? To be clearer, I am asking for something like this:

I am looking for any other, better option than doing this manually:

codeforester's user avatar

  • 3 'assing' != 'assign' , although that's a very amusing typo –  jonrsharpe Commented Jul 15, 2015 at 9:15

5 Answers 5

Simply type it out:

Python employs assignment unpacking when you have an iterable being assigned to multiple variables like above.

In Python3.x this has been extended, as you can also unpack to a number of variables that is less than the length of the iterable using the star operator:

NDevox's user avatar

Totally agree with NDevox's answer

I think it is also worth to mention that if you only need part of the list e.g only the second and last element from the list, you could do

r0n9's user avatar

a, b, c, d = myList is what you want.

Basically, the function returns a tuple, which is similar to a list - because it is an iterable.

This works with all iterables btw. And you need to know the length of the iterable when using it.

AbdealiLoKo's user avatar

  • This will fail with a ValueError in case myList doesn't exactly have items in it. –  codeforester Commented Nov 22, 2020 at 3:35

One trick is to use the walrus operator in Python 3.8 so that you still have the my_list variable. And make it a one-line operation.

PS: Using camelCase (myList) is not pythonic too.

What's new in Python 3.8 : https://docs.python.org/3/whatsnew/3.8.html

Haja Ny Aina Lorenzo RAMAROMAN's user avatar

You can also use a dictionary. This was if you have more elements in a list, you don't have to waste time hardcoding that.

Now we can access variables in this dictionary like so.

Buddy Bob's user avatar

Not the answer you're looking for? Browse other questions tagged python list or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Why can't I modify/repair Enclave Hellfire Power Armour Pieces with the AWKCR mod installed?
  • Does it ever make sense to have a one-to-one obligatory relationship in a relational database?
  • Power Over Ethernet (POE) router to run multiple cameras on a single Ethernet cable?
  • Will running a dehumidifier in a basement impact room temperature?
  • Is Wild Shape affected by Moonbeam?
  • Usage of つもりだ with the past verb
  • Why is it surprising that the CMB is so homogeneous?
  • Man who can't tell right from wrong gets experimental surgery
  • Middle path of buddha
  • Can Ubuntu 24.04 be compromised?
  • Adjusting water quanity according to whether I soak rice before cooking
  • How does NASA calculate trajectory at planetary atmosphere entry
  • Uppercase, lowercase – "in any case"?
  • dd backup fails with "File too large" error despite ample free space on FAT32 partition
  • Recent Zombie apocalypse E-book or Web novel. MC at a college rescues a couple girls then they head to Gym where other students have gathered
  • The goal of this ear training (voice leading) material
  • Why does lottery write "in trust" on winner's cheque?
  • Can you perceive when a creature "starts its turn"?
  • How safe is the runastool.exe, any known issues?
  • Hochschild cohomology and differential operators
  • Would all disagreements vanish if everyone had access to the same information and followed the same reasoning process?
  • What is this general prohibition/slash symbol on my Xcode app
  • How fast to play Rachmaninoff’s Études-Tableaux, Op. 33 No. 5 in G minor?
  • If-then-else statement with page number as the condition

python assignment with list

COMMENTS

  1. python

    2. list[:] specifies a range within the list, in this case it defines the complete range of the list, i.e. the whole list and changes them. list=range(100), on the other hand, kind of wipes out the original contents of list and sets the new contents. But try the following:

  2. Python's list Data Type: A Deep Dive With Examples

    Python's list is a flexible, versatile, powerful, and popular built-in data type. It allows you to create variable-length and mutable sequences of objects. In a list, you can store objects of any type. You can also mix objects of different types within the same list, although list elements often share the same type.

  3. Python List Exercise with Solution [10 Exercise Questions]

    Exercise 1: Reverse a list in Python. Exercise 2: Concatenate two lists index-wise. Exercise 3: Turn every item of a list into its square. Exercise 4: Concatenate two lists in the following order. Exercise 5: Iterate both lists simultaneously. Exercise 6: Remove empty strings from the list of strings.

  4. Python's Assignment Operator: Write Robust Assignments

    Implicit Assignments in Python. Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors. Whenever you complete an action in the following list, Python runs an implicit assignment for you: Define or call a function

  5. Different Forms of Assignment Statements in Python

    6. Multiple- target assignment: In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT. 75 75. 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment. OUTPUT.

  6. How To Use Assignment Expressions in Python

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

  7. The Walrus Operator: Python's Assignment Expressions

    Each new version of Python adds new features to the language. Back when Python 3.8 was released, the biggest change was the addition of assignment expressions.Specifically, the := operator gave you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an in-depth introduction to the walrus operator.

  8. Python Lists

    Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. ... Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point ...

  9. 5. Data Structures

    The list data type has some more methods. Here are all of the methods of list objects: list. append (x) Add an item to the end of the list. Equivalent to a[len(a):] = [x]. list. extend (iterable) Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable. list. insert (i, x) Insert an item at a given position.

  10. Python List: How To Create, Sort, Append, Remove, And More

    Using the list() function. Python lists, like all Python data types, are objects. The list class is called 'list', and it has a lowercase L. If you want to convert another Python object to a list, you can use the list() function, which is actually the constructor of the list class itself. This function takes one argument: an iterable object.

  11. Python Exercises, Practice, Challenges

    These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.

  12. Assignment Operators in Python

    The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.

  13. python

    Assigning to lst[lst.index(row)] results in O(n²) performance instead of O(n), and may cause errors if the list contains multiple identical items. Instead, assign a new list, constructed with a list comprehension or map: lst = [1,2,3,4] doubled = [n*2 for n in lst] Alternatively, you can use enumerate if you really want to modify the original ...

  14. Python List (With Examples)

    Python lists store multiple data together in a single variable. In this tutorial, we will learn about Python lists (creating lists, changing list items, removing items, and other list operations) with the help of examples.

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

  16. Python Assignment Operators

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

  17. assignment operator about list in Python

    Assignment to a bare name in Python (name = ...) is a different operation than assignment to anything else. In particular it is different from item assignment (name[0] = ...) and attribute assignment (name.attr = ...). They all use the equal sign, but the latter two are manipulable with hooks (__setitem__ and __setattr__), can call arbitrary ...

  18. PEP 572

    Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example: foo(x = y := f(x)) # INVALID foo(x=(y := f(x))) # Valid, though probably confusing. This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

  19. Dict built-in get/set methods for nested keys

    apparently, there is no built-in dict method (let's call it .nestkey) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures,. e.g., dic_1.nestkey(list_of_keys_A) = value instead of manually doing dic_1["key_1"]["subkey_2"]["subsubkey_3"] = value. this is not to be confused with level-1 assignment: dic_1["key_1"] = value_1 ...

  20. Lists vs Tuples in Python

    The built-in list class provides a mutable data type. Being mutable means that once you create a list object, you can add, delete, shift, and move elements around at will. Python provides many ways to modify lists, as you'll learn in a moment. Unlike lists, tuples are immutable, meaning that you can't change a tuple once it has been created.

  21. Optimizing Airport Gate Assignments Using MORL with Python

    Efficient gate assignments can transform air travel experiences, making journeys smoother and more enjoyable. In this ... This blog assumes familiarity with Reinforcement Learning (RL), Markov Decision Process (MDP) and Python. Part 1 of this series defines the problem, provides an overview of the solution, and covers environment definition ...

  22. Python error: IndexError: list assignment index out of range

    Your list starts out empty because of this: a = [] then you add 2 elements to it, with this code: a.append(3) a.append(7) this makes the size of the list just big enough to hold 2 elements, the two you added, which has an index of 0 and 1 (python lists are 0-based). In your code, further down, you then specify the contents of element j which ...

  23. Cubs activate RHP Hayden Wesneski, designate RHP Shawn Armstrong for

    CHICAGO - The Chicago Cubs today activated right-handed pitcher Hayden Wesneski from the 15-day injured list and designated right-handed pitcher Shawn Armstrong for assignment. Wesneski, 26, was placed on the injured list July 20 with a right forearm strain. In 25 appearances for the Cubs this season - seven starts

  24. python

    4. Python employs assignment unpacking when you have an iterable being assigned to multiple variables like above. In Python3.x this has been extended, as you can also unpack to a number of variables that is less than the length of the iterable using the star operator: >>> a,b,*c = [1,2,3,4] >>> a. 1. >>> b. 2.