The Wayback Machine - https://web.archive.org/web/20240710045736/https://www.geeksforgeeks.org/different-forms-of-assignment-statements-in-python/
Open In App

Different Forms of Assignment Statements in Python

Last Updated : 10 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object.

There are some important properties of assignment in Python :-

  • Assignment creates object references instead of copying the objects.
  • Python creates a variable name the first time when they are assigned a value.
  • Names must be assigned before being referenced.
  • There are some operations that perform assignments implicitly.

Assignment statement forms :-

1. Basic form:

This form is the most common form.




student = 'Geeks'
print(student)


OUTPUT

Geeks

2. Tuple assignment:




# equivalent to: (x, y) = (50, 100)
x, y = 50, 100  
  
print('x = ', x)
print('y = ', y)


OUTPUT

x = 50 
y = 100

When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively.

3. List assignment:

This works in the same way as the tuple assignment.




[x, y] = [2, 4]
  
print('x = ', x)
print('y = ', y)


OUTPUT

x = 2
y = 4

4. Sequence assignment:

In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position.




a, b, c = 'HEY'
  
print('a = ', a)
print('b = ', b)
print('c = ', c)


OUTPUT

a = H
b = E
c = Y

5. Extended Sequence unpacking:

It allows us to be more flexible in how we select portions of a sequence to assign.




p, *q = 'Hello'
  
print('p = ', p)
print('q = ', q)


Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names.

OUTPUT

p = H
q = ['e', 'l', 'l', 'o']

This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part.




ranks = ['A', 'B', 'C', 'D']
first, *rest = ranks
  
print("Winner: ", first)
print("Runner ups: ", ', '.join(rest))


OUTPUT

Winner: A
Runner ups: B, C, D

6. Multiple- target assignment:




x = y = 75
  
print(x, y)


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.




x = 2
  
# equivalent to: x = x + 1
x += 1  
  
print(x)


OUTPUT

3

There are several other augmented assignment forms:

-=, **=, &=, etc.


Similar Reads

Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
8 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
A += B Assignment Riddle in Python
Predict the output of these two expressions on Python console On console Geek = (1, 2, [8, 9]) Geek[2] += [3, 4] Output: Explanation: Look at the bytecode Python generates for the expression s[a] += b. It becomes clear how that happens. It works step by step Put the value of s[a] on Top Of Stack(TOS). Perform TOS += b. This succeeds, If TOS refers
1 min read
Python | Priority key assignment in dictionary
Sometimes, while working with dictionaries, we have an application in which we need to assign a variable with a single value that would be from any of given keys, whichever occurs first in priority. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This task can be performed in a brute force manner using loop. I
4 min read
Python - Maximum value assignment in Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign to the outer key, the item with maximum value in inner keys. This kind of problem can occur in day-day programming and web development domains. Let's discuss a way in which this task can be performed. Input : test_dict = {'Manjeet': {'English': 19, '
3 min read
Python - Sequence Assignment to Words
Given a String of words, assign an index to each word. Input : test_str = 'geeksforgeeks is best' Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'} Explanation : Index assigned to each word. Input : test_str = 'geeksforgeeks best' Output : {0: 'geeksforgeeks', 1: 'best'} Explanation : Index assigned to each word. Method #1: Using enumerate() + dict
5 min read
Python - Minimum value key assignment
Given two dictionaries, the task is to write a Python program to assign minimum values for matching keys from both dictionaries. Examples: Input : test_dict1 = {"gfg" : 1, "is" : 7, "best" : 8}, test_dict2 = {"gfg" : 2, "is" : 2, "best" : 10}Output : {"gfg" : 1, "is" : 2, "best" : 8}Explanation : Minimum of 1 and 2 is 1, hence, gfg is assigned with
5 min read
Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Python Indexerror: list assignment index out of range Solution
In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range. Python Indexerror: list assignment index out of range ExampleIf ‘fruits’ is a list, fruits=[‘Apple’,’ Banan
3 min read
UnboundLocalError Local variable Referenced Before Assignment in Python
Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the "UnboundLocalError" raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLo
4 min read
Practice Tags :
three90RightbarBannerImg