Multiple assignment in Python: Assign multiple values or the same value to multiple variables

In Python, the = operator is used to assign values to variables.

You can assign values to multiple variables in one line.

Assign multiple values to multiple variables

Assign the same value to multiple variables.

You can assign multiple values to multiple variables by separating them with commas , .

You can assign values to more than three variables, and it is also possible to assign values of different data types to those variables.

When only one variable is on the left side, values on the right side are assigned as a tuple to that variable.

If the number of variables on the left does not match the number of values on the right, a ValueError occurs. You can assign the remaining values as a list by prefixing the variable name with * .

For more information on using * and assigning elements of a tuple and list to multiple variables, see the following article.

  • Unpack a tuple and list in Python

You can also swap the values of multiple variables in the same way. See the following article for details:

  • Swap values ​​in a list or values of variables in Python

You can assign the same value to multiple variables by using = consecutively.

For example, this is useful when initializing multiple variables with the same value.

After assigning the same value, you can assign a different value to one of these variables. As described later, be cautious when assigning mutable objects such as list and dict .

You can apply the same method when assigning the same value to three or more variables.

Be careful when assigning mutable objects such as list and dict .

If you use = consecutively, the same object is assigned to all variables. Therefore, if you change the value of an element or add a new element in one variable, the changes will be reflected in the others as well.

If you want to handle mutable objects separately, you need to assign them individually.

after c = []; d = [] , c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d .) 3. Data model — Python 3.11.3 documentation

You can also use copy() or deepcopy() from the copy module to make shallow and deep copies. See the following article.

  • Shallow and deep copy in Python: copy(), deepcopy()

Related Categories

Related articles.

  • NumPy: arange() and linspace() to generate evenly spaced values
  • Chained comparison (a < x < b) in Python
  • pandas: Get first/last n rows of DataFrame with head() and tail()
  • pandas: Filter rows/columns by labels with filter()
  • Get the filename, directory, extension from a path string in Python
  • Sign function in Python (sign/signum/sgn, copysign)
  • How to flatten a list of lists in Python
  • None in Python
  • Create calendar as text, HTML, list in Python
  • NumPy: Insert elements, rows, and columns into an array with np.insert()
  • Shuffle a list, string, tuple in Python (random.shuffle, sample)
  • Add and update an item in a dictionary in Python
  • Cartesian product of lists in Python (itertools.product)
  • Remove a substring from a string in Python
  • pandas: Extract rows that contain specific strings from a DataFrame
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Provide Multiple Statements on a Single Line in Python

Python is known for its readability and simplicity, allowing developers to express concepts concisely. While it generally encourages clear and straightforward code, there are scenarios where you might want to execute multiple statements on a single line. In this article, we'll explore the logic, and syntax, and provide different examples of how to achieve this in Python.

What are Multiple Statements on a Single Line?

The key to placing multiple statements on a single line in Python is to use a semicolon (;) to separate each statement. This allows you to execute multiple commands within the same line, enhancing code compactness. However, it's important to use this feature judiciously, as overly complex code can lead to reduced readability.

Syntax: The basic syntax for placing multiple statements on a single line is as follows:

How To Provide Multiple Statements On A Single Line In Python?

Below, are the methods of How To Provide Multiple Statements On A Single Line In Python .

  • Variable Assignment & Print Statement
  • Conditional Statements
  • Loop with Break Statement

Variable Assignment and Print Statement

In this example, three statements are executed on a single line. First, we assign the value 5 to the variable x , then we assign 10 to the variable y , and finally, we print the sum of x and y .

Multiple Statements On A Single Line Using Conditional Statements

Here, a conditional statement is used to determine eligibility based on the value of the variable age . The result is assigned to the variable message , and it is printed in a single line.

Multiple Statements On A Single Line Using Loop with Break Statement

In this example, a loop iterates through the numbers list, prints each number, and checks if it equals the target . If the target is found, the found variable is set to True , and the loop is terminated with the break statement .

Multiple Statements On A Single Line Using List Comprehension

In this example, a list comprehension is used to generate a list of squares for even numbers in the range from 1 to 5. The result is assigned to the squares variable, and the list is printed on a single line.

While Python emphasizes readability, there are situations where placing multiple statements on a single line can be useful. The semicolon (;) is the key syntax element for achieving this. However, it's crucial to strike a balance between conciseness and readability to ensure maintainability and understanding of the code

author

Similar Reads

  • Python Programs
  • python-basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python variables - assign multiple values, many values to multiple variables.

Python allows you to assign values to multiple variables in one line:

Note: Make sure the number of variables matches the number of values, or else you will get an error.

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking .

Unpack a list:

Learn more about unpacking in our Unpack Tuples Chapter.

Video: Python Variable Names

Python Tutorial on YouTube

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.

IMAGES

  1. Assigning multiple variables in one line in Python

    python multiple assignments on one line

  2. 16 Python_ Assignments

    python multiple assignments on one line

  3. How to Break One Line Into Multiple Lines in Python?

    python multiple assignments on one line

  4. multiple statement on a single line in python

    python multiple assignments on one line

  5. Python One Line With Statement

    python multiple assignments on one line

  6. Python Multiple Assignments

    python multiple assignments on one line

VIDEO

  1. How to comment and uncomment out multiple lines in python

  2. Comprehensive Course on Python's Matplotlib

  3. Multi-line Statement in Python

  4. The Essential Python Line You Must Know!

  5. #Python

  6. Fast Python Multiple Choice Solution