Python Variables

In Python, a variable is a container that stores a value. In other words, variable is the name given to a value, so that it becomes easy to refer a value later on.

Unlike C# or Java, it's not necessary to explicitly define a variable in Python before using it. Just assign a value to a variable using the = operator e.g. variable_name = value . That's it.

The following creates a variable with the integer value.

In the above example, we declared a variable named num and assigned an integer value 10 to it. Use the built-in print() function to display the value of a variable on the console or IDLE or REPL .

In the same way, the following declares variables with different types of values.

Multiple Variables Assignment

You can declare multiple variables and assign values to each variable in a single statement, as shown below.

In the above example, the first int value 10 will be assigned to the first variable x, the second value to the second variable y, and the third value to the third variable z. Assignment of values to variables must be in the same order in they declared.

You can also declare different types of values to variables in a single statement separated by a comma, as shown below.

Above, the variable x stores 10 , y stores a string 'Hello' , and z stores a boolean value True . The type of variables are based on the types of assigned value.

Assign a value to each individual variable separated by a comma will throw a syntax error, as shown below.

Variables in Python are objects. A variable is an object of a class based on the value it stores. Use the type() function to get the class name (type) of a variable.

In the above example, num is an object of the int class that contains integre value 10 . In the same way, amount is an object of the float class, greet is an object of the str class, isActive is an object of the bool class.

Unlike other programming languages like C# or Java, Python is a dynamically-typed language, which means you don't need to declare a type of a variable. The type will be assigned dynamically based on the assigned value.

The + operator sums up two int variables, whereas it concatenates two string type variables.

Object's Identity

Each object in Python has an id. It is the object's address in memory represented by an integer value. The id() function returns the id of the specified object where it is stored, as shown below.

Variables with the same value will have the same id.

Thus, Python optimize memory usage by not creating separate objects if they point to same value.

Naming Conventions

Any suitable identifier can be used as a name of a variable, based on the following rules:

  • The name of the variable should start with either an alphabet letter (lower or upper case) or an underscore (_), but it cannot start with a digit.
  • More than one alpha-numeric characters or underscores may follow.
  • The variable name can consist of alphabet letter(s), number(s) and underscore(s) only. For example, myVar , MyVar , _myVar , MyVar123 are valid variable names, but m*var , my-var , 1myVar are invalid variable names.
  • Variable names in Python are case sensitive. So, NAME , name , nAME , and nAmE are treated as different variable names.
  • Variable names cannot be a reserved keywords in Python.
  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

different types of variable assignment in python

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles

Leon Lovett

Leon Lovett

Python Variables – A Guide to Variable Assignment and Naming

a computer monitor sitting on top of a wooden desk

In Python, variables are essential elements that allow developers to store and manipulate data. When writing Python code, understanding variable assignment and naming conventions is crucial for effective programming.

Python variables provide a way to assign a name to a value and use that name to reference the value later in the code. Variables can be used to store various types of data, including numbers, strings, and lists.

In this article, we will explore the basics of Python variables, including variable assignment and naming conventions. We will also dive into the different variable types available in Python and how to use them effectively.

Key Takeaways

  • Python variables are used to store and manipulate data in code.
  • Variable assignment allows developers to assign a name to a value and reference it later.
  • Proper variable naming conventions are essential for effective programming.
  • Python supports different variable types, including integers, floats, strings, and lists.

Variable Assignment in Python

Python variables are created when a value is assigned to them using the equals sign (=) operator. For example, the following code snippet assigns the integer value 5 to the variable x :

From this point forward, whenever x is referenced in the code, it will have the value 5.

Variables can also be assigned using other variables or expressions. For example, the following code snippet assigns the value of x plus 2 to the variable y :

It is important to note that variables in Python are dynamically typed, meaning that their type can change as the program runs. For example, the following code snippet assigns a string value to the variable x , then later reassigns it to an integer value:

x = "hello" x = 7

Common Mistakes in Variable Assignment

One common mistake is trying to reference a variable before it has been assigned a value. This will result in a NameError being raised. For example:

print(variable_name) NameError: name ‘variable_name’ is not defined

Another common mistake is assigning a value to the wrong variable name. For example, the following code snippet assigns the value 5 to the variable y instead of x :

y = 5 print(x) NameError: name ‘x’ is not defined

To avoid these mistakes, it is important to carefully review code and double-check variable names and values.

Using Variables in Python

Variables are used extensively in Python code for a variety of purposes, from storing user input to performing complex calculations. The following code snippet demonstrates the basic usage of variables in a simple addition program:

number1 = input("Enter the first number: ") number2 = input("Enter the second number: ") sum = float(number1) + float(number2) print("The sum of", number1, "and", number2, "is", sum)

This program prompts the user to enter two numbers, converts them to floats using the float() function, adds them together, and prints the result using the print() function.

Variables can also be used in more complex operations, such as string concatenation and list manipulation. The following code snippet demonstrates how variables can be used to combine two strings:

greeting = "Hello" name = "Alice" message = greeting + ", " + name + "!" print(message)

This program defines two variables containing a greeting and a name, concatenates them using the plus (+) operator, and prints the result.

Variable Naming Conventions in Python

In Python, proper variable naming conventions are crucial for writing clear and maintainable code. Consistently following naming conventions makes code more readable and easier to understand, especially when working on large projects with many collaborators. Here are some commonly accepted conventions:

ConventionExample
Lowercasefirst_name
UppercaseLAST_NAME
Camel CasefirstName
Snake Casefirst_name

It’s recommended to use lowercase or snake case for variable names as they are easier to read and more commonly used in Python. Camel case is common in other programming languages, but can make Python code harder to read.

Variable names should be descriptive and meaningful. Avoid using abbreviations or single letters, unless they are commonly understood, like “i” for an iterative variable in a loop. Using descriptive names will make your code easier to understand and maintain by you and others.

Lastly, it’s a good practice to avoid naming variables with reserved words in Python such as “and”, “or”, and “not”. Using reserved words can cause errors in your code, making it hard to debug.

Scope of Variables in Python

Variables in Python have a scope, which dictates where they can be accessed and used within a code block. Understanding variable scope is important for writing efficient and effective code.

Local Variables in Python

A local variable is created within a particular code block, such as a function. It can only be accessed within that block and is destroyed when the block is exited. Local variables can be defined using the same Python variable assignment syntax as any other variable.

Example: def my_function():     x = 10     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 NameError: name ‘x’ is not defined

In the above example, the variable ‘x’ is a local variable that is defined within the function ‘my_function()’. It cannot be accessed outside of that function, which is why the second print statement results in an error.

Global Variables in Python

A global variable is a variable that can be accessed from anywhere within a program. These variables are typically defined outside of any code block, at the top level of the program. They can be accessed and modified from any code block within the program.

Example: x = 10 def my_function():     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 Value outside function: 10

In the above example, the variable ‘x’ is a global variable that is defined outside of any function. It can be accessed from within the ‘my_function()’ as well as from outside it.

When defining a function, it is possible to access and modify a global variable from within the function using the ‘global’ keyword.

Example: x = 10 def my_function():     global x     x = 20 my_function() print(x) Output: 20

In the above example, the ‘global’ keyword is used to indicate that the variable ‘x’ inside the function is the same as the global variable ‘x’. The function modifies the global variable, causing the final print statement to output ’20’ instead of ’10’.

One of the most fundamental concepts in programming is the use of variables. In Python, variables allow us to store and manipulate data efficiently. Here are some practical examples of how to use variables in Python:

Mathematical Calculations

Variables are often used to perform mathematical calculations in Python. For instance, we can assign numbers to variables and then perform operations on those variables. Here’s an example:

x = 5 y = 10 z = x + y print(z) # Output: 15

In this code, we have assigned the value 5 to the variable x and the value 10 to the variable y. We then create a new variable z by adding x and y together. Finally, we print the value of z, which is 15.

String Manipulation

Variables can also be used to manipulate strings in Python. Here is an example:

first_name = “John” last_name = “Doe” full_name = first_name + ” ” + last_name print(full_name) # Output: John Doe

In this code, we have assigned the strings “John” and “Doe” to the variables first_name and last_name respectively. We then create a new variable full_name by combining the values of first_name and last_name with a space in between. Finally, we print the value of full_name, which is “John Doe”.

Working with Data Structures

Variables are also essential when working with data structures such as lists and dictionaries in Python. Here’s an example:

numbers = [1, 2, 3, 4, 5] sum = 0 for num in numbers:     sum += num print(sum) # Output: 15

In this code, we have assigned a list of numbers to the variable numbers. We then create a new variable sum and initialize it to 0. We use a for loop to iterate over each number in the list, adding it to the sum variable. Finally, we print the value of sum, which is 15.

As you can see, variables are an essential tool in Python programming. By using them effectively, you can manipulate data and perform complex operations with ease.

Variable Types in Python

Python is a dynamically typed language, which means that variables can be assigned values of different types without explicit type declaration. Python supports a wide range of variable types, each with its own unique characteristics and uses.

Numeric Types:

Python supports several numeric types, including integers, floats, and complex numbers. Integers are whole numbers without decimal points, while floats are numbers with decimal points. Complex numbers consist of a real and imaginary part, expressed as a+bi.

TypeExampleDescription
int42Represent whole numbers
float3.14Represent decimal numbers
complex1+2jRepresent numbers with real and imaginary parts

Sequence Types:

Python supports several sequence types, including strings, lists, tuples, and range objects. Strings are sequences of characters, while lists and tuples are sequences of values of any type. Range objects are used to represent sequences of numbers.

TypeExampleDescription
str‘hello’Represents text strings
list[1, 2, 3]Represents ordered collections of values
tuple(1, 2, 3)Represents immutable ordered collections of values
rangerange(0, 10)Represents a range of numbers

Mapping Types:

Python supports mapping types, which are used to store key-value pairs. The most commonly used mapping type is the dictionary, which supports efficient lookup of values based on their associated keys.

TypeExampleDescription
dict{‘name’: ‘John’, ‘age’: 30}Represents a collection of key-value pairs

Boolean Type:

Python supports a Boolean type, which is used to represent truth values. The Boolean type has two possible values: True and False.

Python has a special value called None, which represents the absence of a value. This type is often used to indicate the result of functions that do not return a value.

Understanding the different variable types available in Python is essential for effective coding. Each type has its own unique properties and uses, and choosing the right type for a given task can help improve code clarity, efficiency, and maintainability.

Python variables are a fundamental concept that every aspiring Python programmer must understand. In this article, we have covered the basics of variable assignment and naming conventions in Python. We have also explored the scope of variables and their different types.

It is important to remember that variables play a crucial role in programming, and their effective use can make your code more efficient and easier to read. Proper naming conventions and good coding practices can also help prevent errors and improve maintainability.

As you continue to explore the vast possibilities of Python programming, we encourage you to practice using variables in your code. With a solid understanding of Python variables, you will be well on your way to becoming a proficient Python programmer.

Similar Posts

An Introduction to Python’s Core Data Types

An Introduction to Python’s Core Data Types

Python is a widely used programming language that is renowned for its simplicity and accessibility. At the core of Python lies its data types, which are fundamental units that enable programmers to store and manipulate information. Understanding Python data types is essential for effective programming in the language. This article provides an introduction to Python’s…

Python Modules and Packages Explained

Python Modules and Packages Explained

Python programming has become increasingly popular over the years, and for good reason. It is a high-level and versatile language with a wide range of applications, from web development to data analysis. One of the key features of Python that sets it apart from other programming languages is its use of modules and packages. In…

Object Oriented Programming in Python – A Beginner’s Guide

Object Oriented Programming in Python – A Beginner’s Guide

Python is a versatile programming language that offers support for object-oriented programming (OOP). OOP is a programming paradigm that provides a modular and reusable way to design software. In this article, we will provide a beginner’s guide to object-oriented programming in Python with a focus on Python classes. Python classes are the building blocks of…

Introduction to Anonymous Functions in Python

Introduction to Anonymous Functions in Python

Python is a popular language used widely for coding because of its simplicity and versatility. One of the most powerful aspects of Python is its ability to use lambda functions, also known as anonymous functions. In this article, we will explore the concept of anonymous functions in Python, and how they can help simplify your…

Coding Reusable Logic with Python Functions

Coding Reusable Logic with Python Functions

In the world of coding, efficiency and reusability are paramount. With Python functions, you can achieve both. Functions are code blocks that perform specific tasks and can be called multiple times throughout your program. This means you can write a block of code once and reuse it whenever you need it, saving you valuable time…

A Guide to Python’s String Methods

A Guide to Python’s String Methods

Python is a powerful programming language for text processing, thanks to its rich set of string methods. Python string methods are built-in functions that allow you to manipulate and transform text data in various ways. In this article, we will explore Python’s string methods in depth, discussing their functionalities and demonstrating their usage with examples….

  • Module 2: The Essentials of Python »
  • Variables & Assignment
  • View page source

Variables & Assignment 

There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.

Variables permit us to write code that is flexible and amendable to repurpose. Suppose we want to write code that logs a student’s grade on an exam. The logic behind this process should not depend on whether we are logging Brian’s score of 92% versus Ashley’s score of 94%. As such, we can utilize variables, say name and grade , to serve as placeholders for this information. In this subsection, we will demonstrate how to define variables in Python.

In Python, the = symbol represents the “assignment” operator. The variable goes to the left of = , and the object that is being assigned to the variable goes to the right:

Attempting to reverse the assignment order (e.g. 92 = name ) will result in a syntax error. When a variable is assigned an object (like a number or a string), it is common to say that the variable is a reference to that object. For example, the variable name references the string "Brian" . This means that, once a variable is assigned an object, it can be used elsewhere in your code as a reference to (or placeholder for) that object:

Valid Names for Variables 

A variable name may consist of alphanumeric characters ( a-z , A-Z , 0-9 ) and the underscore symbol ( _ ); a valid name cannot begin with a numerical value.

var : valid

_var2 : valid

ApplePie_Yum_Yum : valid

2cool : invalid (begins with a numerical character)

I.am.the.best : invalid (contains . )

They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names:

for , while , break , pass , continue

in , is , not

if , else , elif

def , class , return , yield , raises

import , from , as , with

try , except , finally

There are other unicode characters that are permitted as valid characters in a Python variable name, but it is not worthwhile to delve into those details here.

Mutable and Immutable Objects 

The mutability of an object refers to its ability to have its state changed. A mutable object can have its state changed, whereas an immutable object cannot. For instance, a list is an example of a mutable object. Once formed, we are able to update the contents of a list - replacing, adding to, and removing its elements.

To spell out what is transpiring here, we:

Create (initialize) a list with the state [1, 2, 3] .

Assign this list to the variable x ; x is now a reference to that list.

Using our referencing variable, x , update element-0 of the list to store the integer -4 .

This does not create a new list object, rather it mutates our original list. This is why printing x in the console displays [-4, 2, 3] and not [1, 2, 3] .

A tuple is an example of an immutable object. Once formed, there is no mechanism by which one can change of the state of a tuple; and any code that appears to be updating a tuple is in fact creating an entirely new tuple.

Mutable & Immutable Types of Objects 

The following are some common immutable and mutable objects in Python. These will be important to have in mind as we start to work with dictionaries and sets.

Some immutable objects

numbers (integers, floating-point numbers, complex numbers)

“frozen”-sets

Some mutable objects

dictionaries

NumPy arrays

Referencing a Mutable Object with Multiple Variables 

It is possible to assign variables to other, existing variables. Doing so will cause the variables to reference the same object:

What this entails is that these common variables will reference the same instance of the list. Meaning that if the list changes, all of the variables referencing that list will reflect this change:

We can see that list2 is still assigned to reference the same, updated list as list1 :

In general, assigning a variable b to a variable a will cause the variables to reference the same object in the system’s memory, and assigning c to a or b will simply have a third variable reference this same object. Then any change (a.k.a mutation ) of the object will be reflected in all of the variables that reference it ( a , b , and c ).

Of course, assigning two variables to identical but distinct lists means that a change to one list will not affect the other:

Reading Comprehension: Does slicing a list produce a reference to that list?

Suppose x is assigned a list, and that y is assigned a “slice” of x . Do x and y reference the same list? That is, if you update part of the subsequence common to x and y , does that change show up in both of them? Write some simple code to investigate this.

Reading Comprehension: Understanding References

Based on our discussion of mutable and immutable objects, predict what the value of y will be in the following circumstance:

Reading Comprehension Exercise Solutions: 

Does slicing a list produce a reference to that list?: Solution

Based on the following behavior, we can conclude that slicing a list does not produce a reference to the original list. Rather, slicing a list produces a copy of the appropriate subsequence of the list:

Understanding References: Solutions

Integers are immutable, thus x must reference an entirely new object ( 9 ), and y still references 3 .

Python Variables – The Complete Beginner's Guide

Reed Barger

Variables are an essential part of Python. They allow us to easily store, manipulate, and reference data throughout our projects.

This article will give you all the understanding of Python variables you need to use them effectively in your projects.

If you want the most convenient way to review all the topics covered here, I've put together a helpful cheatsheet for you right here:

Download the Python variables cheatsheet (it takes 5 seconds).

What is a Variable in Python?

So what are variables and why do we need them?

Variables are essential for holding onto and referencing values throughout our application. By storing a value into a variable, you can reuse it as many times and in whatever way you like throughout your project.

You can think of variables as boxes with labels, where the label represents the variable name and the content of the box is the value that the variable holds.

In Python, variables are created the moment you give or assign a value to them.

How Do I Assign a Value to a Variable?

Assigning a value to a variable in Python is an easy process.

You simply use the equal sign = as an assignment operator, followed by the value you want to assign to the variable. Here's an example:

In this example, we've created two variables: country and year_founded. We've assigned the string value "United States" to the country variable and integer value 1776 to the year_founded variable.

There are two things to note in this example:

  • Variables in Python are case-sensitive . In other words, watch your casing when creating variables, because Year_Founded will be a different variable than year_founded even though they include the same letters
  • Variable names that use multiple words in Python should be separated with an underscore _ . For example, a variable named "site name" should be written as "site name" ._ This convention is called snake case (very fitting for the "Python" language).

How Should I Name My Python Variables?

There are some rules to follow when naming Python variables.

Some of these are hard rules that must be followed, otherwise your program will not work, while others are known as conventions . This means, they are more like suggestions.

Variable naming rules

  • Variable names must start with a letter or an underscore _ character.
  • Variable names can only contain letters, numbers, and underscores.
  • Variable names cannot contain spaces or special characters.

Variable naming conventions

  • Variable names should be descriptive and not too short or too long.
  • Use lowercase letters and underscores to separate words in variable names (known as "snake_case").

What Data Types Can Python Variables Hold?

One of the best features of Python is its flexibility when it comes to handling various data types.

Python variables can hold various data types, including integers, floats, strings, booleans, tuples and lists:

Integers are whole numbers, both positive and negative.

Floats are real numbers or numbers with a decimal point.

Strings are sequences of characters, namely words or sentences.

Booleans are True or False values.

Lists are ordered, mutable collections of values.

Tuples are ordered, immutable collections of values.

There are more data types in Python, but these are the most common ones you will encounter while working with Python variables.

Python is Dynamically Typed

Python is what is known as a dynamically-typed language. This means that the type of a variable can change during the execution of a program.

Another feature of dynamic typing is that it is not necessary to manually declare the type of each variable, unlike other programming languages such as Java.

You can use the type() function to determine the type of a variable. For instance:

What Operations Can Be Performed?

Variables can be used in various operations, which allows us to transform them mathematically (if they are numbers), change their string values through operations like concatenation, and compare values using equality operators.

Mathematic Operations

It's possible to perform basic mathematic operations with variables, such as addition, subtraction, multiplication, and division:

It's also possible to find the remainder of a division operation by using the modulus % operator as well as create exponents using the ** syntax:

String operators

Strings can be added to one another or concatenated using the + operator.

Equality comparisons

Values can also be compared in Python using the < , > , == , and != operators.

These operators, respectively, compare whether values are less than, greater than, equal to, or not equal to each other.

Finally, note that when performing operations with variables, you need to ensure that the types of the variables are compatible with each other.

For example, you cannot directly add a string and an integer. You would need to convert one of the variables to a compatible type using a function like str() or [int()](https://www.freecodecamp.org/news/python-string-to-int-convert-a-string-example/) .

Variable Scope

The scope of a variable refers to the parts of a program where the variable can be accessed and modified. In Python, there are two main types of variable scope:

Global scope : Variables defined outside of any function or class have a global scope. They can be accessed and modified throughout the program, including within functions and classes.

Local scope : Variables defined within a function or class have a local scope. They can only be accessed and modified within that function or class.

In this example, attempting to access local_var outside of the function_with_local_var function results in a NameError , as the variable is not defined in the global scope.

Don't be afraid to experiment with different types of variables, operations, and scopes to truly grasp their importance and functionality. The more you work with Python variables, the more confident you'll become in applying these concepts.

Finally, if you want to fully learn all of these concepts, I've put together for you a super helpful cheatsheet that summarizes everything we've covered here.

Just click the link below to grab it for free. Enjoy!

Download the Python variables cheatsheet

Become a Professional React Developer

React is hard. You shouldn't have to figure it out yourself.

I've put everything I know about React into a single course, to help you reach your goals in record time:

Introducing: The React Bootcamp

It’s the one course I wish I had when I started learning React.

Click below to try the React Bootcamp for yourself:

Click to join the React Bootcamp

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Variable Assignment

Martin Breuss

  • Discussion (8)

Think of a variable as a name attached to a particular object . In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ).

00:00 Welcome to this first section, where we’ll talk about variable assignments in Python. First of all, I just want to mention that I’m going to be using the IPython shell.

00:09 The reason for that is just that it adds a bit of colors to the prompt and makes it a bit easier to see which types we’re working with, but you don’t need to do this install that I’m going to show you in just a second.

00:19 You can just use your normal Python interpreter and it’s going to work all the same. If you want to install IPython, all you need to do is go to your terminal and type pip3 install ipython , press Enter, and then wait until it installs.

00:36 I already got it installed. And then instead of typing python to get into the interpreter, you’re going to type ipython .

00:46 It gives us the same functionality, only you see there’s some colors involved and it looks a bit nicer. I can do clear and clear my screen. So it’s going to make it a bit easier for you to follow, but that’s all.

00:58 So, first stop: a standard variable assignment in Python. Unlike other languages, in Python this is very simple. We don’t need to declare a variable, all we need to do is give it a name, put the equal sign ( = ) and then the value that we want to assign. That’s it.

01:15 That’s a variable assignment in Python. I just assigned the value 300 to the variable n . So now I can print(n) and get the result.

01:26 Or, since I’m in an interpreter session, I can just put in n and it shows me that the output is going to be 300 . So, that’s the basic, standard variable assignment that you’re going to do many times in Python.

01:38 And it’s nice that you don’t need to declare the variable before. You simply can type it in like this. Now the variable n is referring to the value 300 .

01:48 What happens if I change it? So, I don’t need to stick with 300 through the lifetime of this variable. I can just change it to something else. I can say “Now this is this going to be 400 .”

02:00 Or, in Python, not even the type is fixed, so I can say n = "hello" and change it to a string.

02:10 And this is still all working fine. So you see, it feels very fluid, and this is because Python is a dynamically-typed language, so we don’t need to define types and define variables beforehand and then they’re unchangeable for the rest of the program—but it’s fluid, and we can just start off with n being an integer of the value of 300 and through the lifetime of the program, it can take on a couple of different identities.

02:36 So, apart from the standard variable assignment that we just saw before, n = 300 , we can also use a chained assignment in Python, which makes it quick to assign a couple of variables to the same value.

02:49 And that looks like this.

02:52 I can say n = m = x = y et cetera, and then give it a value. And now all of those variable names point to 400 , so I can say m is 400 , x is 400 , y is 400 , et cetera. That’s what is called a chained assignment in Python.

03:15 Another way is the multiple assignment statement, or multiple assignments, which works a little bit different and there’s something you need to take care of, but I still want to introduce you to it. If you go ahead here, I can assign two values at the same time in one line.

03:32 So I can say a, b = 300, 400 . The comma ( , ) is important, and it’s important that the amount of variables that you’re declaring here on the left side is the same amount of values that you have on the right side.

03:48 I can do this, and now b points to 400 , a points to 300 .

03:54 It doesn’t have to be two, there can be more, but just make sure that every time if you use this multiple assignment statement, that the amount of variables you use left is the same as the amount of values on the right. And as a last point in this section, I want to talk a little bit about variable types.

04:14 I already mentioned that variable types don’t have to be fixed in Python. I can start off with

04:21 n pointing to 300 , which as we know is an integer. Remember, you can always check what the type of a variable is by just saying type() and passing in the variable in there.

04:33 So it gives me as an output that this is an int (integer).

04:37 This is just the same as saying “What’s the type() of 300 or 200 ?” directly— it’s an integer—because all that I’m passing in here is a reference to this object. We’ll talk about this more in the next section.

04:52 But now I can easily change the type of this variable, because all I’m doing is pointing it to a different object. So now n is pointing to a string.

05:01 If I say type(n) now, it will tell me it’s a str (string).

05:08 And the reason for this is that variables in Python are simply references to objects. In the next section, we’ll talk much more what’s important about that and how in Python everything is an object.

05:19 And that it for this section! Let’s do a quick recap. Variable assignments in Python are pretty straightforward. We have the standard variable assignment that just goes <variable name> = <your value> .

05:32 We have another way of doing it that’s called chained assignments, where we can assign a couple of variable names to the same value by just using multiple equal signs.

05:43 Then there’s the multiple assignment statement, which works a little differently, and you have to take care to use commas and the same amount of variable names on the left side as values on the right side.

05:53 It’s going to assign, as expected, n to 300 , m to 400 . And then finally, we talked about variable types, that they are fluid in Python and that you can check what the variable type is by using the type() function.

06:07 And here’s a nice thing to see also, that n is just a pointer to the 300 integer, because we’re going to get the same result if we say type(n) or type(300) .

06:18 They’re both int (integer) objects. And this is a concept that we’re going to talk about more in the upcoming section when we talk about object references. See you over there.

Avatar image for iamscottdavis

iamscottdavis on Dec. 10, 2019

I installed ipython on my chromebook but it won’t run.

Avatar image for Martin Breuss

Martin Breuss RP Team on Dec. 10, 2019

You might have to close and re-open your terminal @iamscottdavis

Avatar image for Geir Arne Hjelle

Geir Arne Hjelle RP Team on Dec. 10, 2019

I’ve recently had some weird issues with prompt_toolkit , one of the dependencies of IPython. Maybe that’s what you’re running into?

I got a cryptic error message like TypeError: __init__() got an unexpected keyword argument 'inputhook' . If this is your problem as well, the best solution should be to update to IPython >= 7.10 which should have fixed this. Another workaround is to downgrade prompt_toolkit to version 2.

See some discussion on github.com/ipython/ipython/issues/11975

If you are having other problems, feel free to post your error messages :)

Avatar image for kiran

kiran on July 18, 2020

if i declare the variable in any one loop in python.

now my question is a is local/global variable? in C it is local variable but what about python? in Python even i declare a variable with in the loop it become a global variable?

Martin Breuss RP Team on July 18, 2020

In Python, it will keep the last value it got assigned within the loop also outside in the global scope. That is why a is still accessible and has a value in your example, also outside of the loop’s scope.

Avatar image for DoubleA

DoubleA on Jan. 20, 2021

Hey Martin,

Thanks for pulling this stuff together and explaining it so clearly. I came accross some sort of a variation of the multiple assignment you discussed. Basically, it seems that the number of variable names and variables can be diffrent. What I mean is this:

then print(a,b,c) gives me the following output:

Am I right saying that, basically, what happens above is that the variable c having an asterisk before it will get assigned a list of the two values, incl. the excessive (‘string’) one?

Referring back to Kiran’s question:

When I run this code:

I see that the globals() function returns, amongst other things, the value of the variables a , b and the last value of the iterable elem . Both variables a and b appear to be visible in the global scope as key-value pairs of the following dict:

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Jan. 21, 2021

@DoubleA The “starred” expression syntax you were referring to before can be used for extended iterable unpacking .

Become a Member to join the conversation.

different types of variable assignment in python

Introduction to Programming

Variables in python.

  • The purpose of a variable is to store information within a program while it is running.
  • A variable is a named storage location in computer memory. Use the name to access the value.
  • To store a value in a variable, use the = operator (called the assignment operator).
  • An = sign in Python is nothing like an equal sign in mathematics. Think of it more like an arrow going from right to left. The expression on the right is evaluated and then stored in the variable named on the left.
  • For example, the line of code hourly_wage = 16.75 stores the value 16.75 in the variable called hourly_wage
  • You can change the value of a variable with another assignment statement, such as hourly_wage = 17.25
  • Every value has a type ( int for integers, float for decimals, str for text). In python, when you store a value in a variable (with = ), that variable then automatically has a type. For example, after the above assignment, hourly_wage is of type float .

Rules and conventions for naming variables in python

  • The first character must be a letter or an underscore. For now, stick to letters for the first character.
  • The remaining characters must be letters, numbers or underscores.
  • No spaces are allowed in variable names.
  • Legal examples: _pressure , pull , x_y , r2d2
  • Invalid examples, these are NOT legal variable names: 4th_dimension , %profit , x*y , four(4) , repo man
  • In python, it's a conventiion to use snake case to name variables. This means that we use all lower-case letters and we separate words in the variable name with underscores. Examples include age , x_coordinate , hourly_wage , user_password
  • If the value stored in a variable is a true constant (in other words, its value will never change throughout the program), then we use all capital letters: COURSE_ENROLLMENT_LIMIT , MAX_PASSWORD_ATTEMPTS .
  • For high quality code, it is crucial that you give descriptive names for variables. The variable names must help the reader of your program understand your intention.

Typical way we visualize variables

We usually draw variables by putting the value in a box, and labelling the box with the name of the variable:

Visual representation of a variable

Types of variables

Each variable has a name, a value, and a type. Types are necessary because different kinds of data are stored differently within the computer's memory. For now, we will learn three different types, for storing signed (positive or negative) whole numbers, signed decimals, and text.

TypeDescriptionExamples
Numerical type Signed integer that stores whole numbers (no decimal)0, 7, -5
Numerical type Signed decimal value0.5, 20.0, -18.2, 2.5e3 = 2.5x10^3
String type (Text) Any number of characters surrounded by or "Hello", 'world', '9'

Creating a variable with an assignment operator

A variable is created or declared when we assign a value to it using the assignment operator = . In python, the code looks like this: variable_name = <value> .

Notice that the left hand side of an assignment must be a variable name. Non-example:

After creating a variable, you can change the value stored in a variable with another assignment operator at any time. This is called reassignment .

Finding out the type of a variable or value

The type() function in python will return the type of either a variable or a value. Here are examples that show how to use it:

The output of the above code will be:

Casting (changing the type) of a variable or value

You can change the type of a value (called “casting”) using the int() , float() and str() functions. For example:

  • int(23.7) (truncates the float value 23.7 to the int value 23. This is different from rounding - the decimal part is discarded, regardless of whether it is larger or smaller than 0.5.
  • float(23) (outputting the result will give 23.0 rather than 23)
  • str(23) (converts the integer 23 to the text "23" )
  • int("23") (converts the string "23" into a numerical integer value 23 )
  • float("23") (converts the string "23" into a numerical decimal value 23.0 )
  • int("23.5") results in an error
  • float("hello") results in an error

Doing arithmetic in python

Here are the basic arithmetic operators in python. In these examples, assume

OperatorDescriptionSyntaxOutput (x=11, y=4)
Addition
Multiplication
Subtraction
Decimal division (type is a
Integer division (result of division is truncated, giving an )
Modulus (remainder when first operand is divided by the second)
Exponentiation (raises the first to the power of the second )

An example of a use of the modulus operator is to determine if an integer is even or odd. Note that if x is an integer, then x%2 takes the value 0 or 1 . So x % 2 == 0 is True when x is even and False when x is odd.

Another example of integer division and modulus: When we divide 3 by 4, we get a quotient of 0 and a remainder of 3. So 3//4 results in 0 and 3%4 results in 3.

Warning note: In python, ^ is not an exponent!

Order of operations

The order of operations in python is similar to the order you are familiar with in math: parentheses, then exponentiation, then multiplication/division/modulus in order from left to right, then addition/subtraction in order from left to right.

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Different Forms of Assignment Statements in Python

Assignment statement in python is the statement used to assign the value to the specified variable. The value assigned to the variable can be of any data type supported by python programming language such as integer, string, float Boolean, list, tuple, dictionary, set etc.

Types of assignment statements

The different types of assignment statements are as follows.

Basic assignment statement

Multiple assignment statement

Augmented assignment statement

Chained assignment statement, unpacking assignment statement, swapping assignment statement.

Let’s see about each one in detail.

Basic Assignment Statement

The most frequently and commonly used is the basic assignment statement. In this type of assignment, we will assign the value to the variable directly. Following is the syntax.

Variable_name is the name of the variable.

value is the any datatype of input value to be assigned to the variable.

In this example, we are assigning a value to the variable using the basic assignment statement in the static manner.

In this example, we will use the dynamic inputting way to assign the value using the basic assignment statement.

Multiple Assignment statement

We can assign multiple values to multiple variables within a single line of code in python. Following is the syntax.

v1,v2,……,vn are the variable names.

val1,val2,……,valn are the values.

In this example, we will assign multiple values to the multiple variables using the multiple assignment statement.

By using the augmented assignment statement, we can combine the arithmetic or bitwise operations with the assignment. Following is the syntax.

variable is the variable name.

value is the input value.

+= is the assignment operator with the arithmetic operator.

In this example, we will use the augmented assignment statement to assign the values to the variable.

By using the chained assignment statement, we can assign a single value to the multiple variables within a single line. Following is the syntax -

v1,v2,v3 are the variable names.

value is the value to be assigned to the variables.

Here is the example to assign the single value to the multiple variables using the chain assignment statement.

We can assign the values given in a list or tuple can be assigned to multiple variables using the unpacking assignment statement. Following is the syntax -

val1,val2,val3 are the values.

In this example, we will assign the values grouped in the list to the multiple variables using the unpacking assignment statement.

In python, we can swap two values of the variables without using any temporary third variable with the help of assignment statement. Following is the syntax.

var1, var2 are the variables.

In the following example, we will assign the values two variables and swap the values with each other.

Niharika Aitam

  • Related Articles
  • What is assignment statements with Integer types in compiler design?
  • Give the different forms of silica in nature.
  • A += B Assignment Riddle in Python
  • Python – Priority key assignment in dictionary
  • Python Program to Minimum Value Key Assignment
  • What is vertical bar in Python bitwise assignment operator?
  • Multiple Statements in Python
  • Multi-Line Statements in Python
  • Loop Control Statements in Python
  • The import Statements in Python
  • What are the different types of conditional statements supported by C#?
  • Compound Assignment Operators in C++
  • Compound assignment operators in C#
  • Short Circuit Assignment in JavaScript
  • Assignment operators in Dart Programming

Kickstart Your Career

Get certified by completing the course

  • Contributors

Variables in Python

Table of contents, variable definition, variable naming convention, variable declaration, character variable, declaring variables’ types, variables and constants, global and local variables defining.

Variables in Python

Variables play a crucial role in Python, as they provide a way to store and manipulate data throughout a program. By assigning values to variables, we can easily refer to and update data as needed, making our code more efficient and readable. Overall, variables are a fundamental concept in Python programming and are essential for any kind of data manipulation and analysis. Let's review this topic in details.

Let's define what a variable is in Python. It is a named location in the computer's memory that stores a value. It is like a container that can hold different types of data, such as numbers, strings or booleans .

To create a variable in Python, you need to give it a name and assign a value to it using the assignment operator = .

In Python, variable names are case sensitive and can be any combination of letters, numbers, and underscores. However, there are guidelines and variable naming conventions in Python that make your code more readable and maintainable:

  • Use lowercase letters for variable names. In Python, it is customary to use lowercase letters for variable names.
  • Use underscores to separate words in variable names. If a variable name consists of more than one word, use underscores to separate them. For example, first_name is a better variable name than firstname
  • Avoid using reserved keywords. Python has reserved keywords that have special meaning in the language, such as if , else , while , and for . Avoid using these keywords as variable names.
  • Use descriptive names for variables. Choose descriptive names that reflect the purpose of the variable. For example, count is a better variable name than c
  • Use singular nouns for variable names. For example, student is a better variable name than students .
  • Be consistent with naming conventions within your code and across your team.

Here are some examples of good variable names in Python:

Remember that good variable naming conventions not only help you set a valid variable name, but also make your code more readable, maintainable, and reduce the risk of bugs.

In Python, you don't need to explicitly declare a variable before using it. You can create a variable simply by assigning a value to it.

However, it is important to note that variables in Python are dynamically typed, which means that the data type of a variable is determined at runtime based on the type of the value assigned to it. This means that the same variable can hold different types of values at different times. For example:

In this example, we first created a variable named y and assigned it the value 5 . We then changed the value of y to a string hello . The program printed the value of y , which is the string hello .

There are nine data types in Python:

  • Floating-point numbers
  • Dictionaries

The first three types can conditionally be combined into numeric group.

Numeric Types

Numeric types are used to represent numbers in Python . There are three types of numeric data types in Python:

  • Integer : Integers are whole numbers without any decimal point. Example: 5, 10, -3.
  • Float : Floats are numbers with decimal points. Example: 2.5, -0.1, 3.14.
  • Complex : Complex numbers are numbers with a real and imaginary part. They are denoted by adding a j at the end of the imaginary part. Example: 2 + 3j, -4j.

Boolean Type

Boolean type is a data type that can have only two values - True or False .

String Type

Strings (also known as string literal) are used to represent text data in Python. They are enclosed in quotes (single or double) and can contain letters, numbers, and special characters. Let's see what a string is with an example:

Lists are used to store a collection of items. They can contain any type of data and are denoted by square brackets.

Tuples are similar to lists, but they are immutable, meaning their contents cannot be changed. They are denoted by parentheses.

Sets are used to store unique values. They are denoted by curly braces.

Dictionary Type

Dictionaries are used to store key-value pairs. Each key is associated with a value, and they are denoted by curly braces with key-value pairs separated by colons.

None is a special data type in Python that represents the absence of a value.

In Python, a character variable is a single character stored in a variable. Unlike some other programming languages, Python does not have a separate data type for characters. Instead, a character is simply a string of length 1 in Python.

To declare a character variable in Python, you can assign a single character to a variable using single quotes, double quotes, or triple quotes. Here are some examples:

In the examples above, char1 , char2 , and char3 are all character variables that store the characters a , b , and c , respectively.

You can also use indexing to extract a single character from a string variable . For example:

In the example above, char is a character variable that stores the first character of the string hello .

As it was mentioned above, Python is a dynamically typed language, which means that you do not need to declare the type of a variable explicitly. Instead, the type of a variable is determined at runtime based on the value it is assigned.

However, starting from Python 3.5, the language includes a syntax for type annotations, which allow you to specify the expected type of a variable. This can be useful for improving code readability, documentation, and type checking.

Here's an example of how you can use type annotations in Python:

Note that type annotations are optional, and Python will still work even if you do not use them. However, using type annotations can help catch certain types of errors at compile time, rather than at runtime.

In Python, variables are used to store data or values that can be changed or updated during the course of the program. On the other hand, constant variables, as the name suggests, are variables that cannot be changed once they are assigned a value.

In Python, there is no specific way to declare a variable or a constant variable, as variables are dynamically typed and their type can change during the program execution. However, a common convention to differentiate between variables and constant variables is to use all capital letters for the latter.

For example, let's say we want to declare a variable to store the age of a person and a constant variable to store the value of pi. We can declare them as follows:

In the above example, age is a variable that can be changed, while PI is a constant variable that cannot be changed once assigned a value.

It is important to note that this convention does not actually make the variable constant, and it is still possible to modify the value of a constant variable in Python. However, following this convention helps in distinguishing between variables that are intended to be changed during the program execution and those that are intended to be constant.

There are two types of variables in Python: global and local .

A global variable in Python is a variable that is defined outside a function and can be accessed by any part of the program, including functions . Global variables in Python have a global scope, which means they are accessible from anywhere in the code.

Here's an example how to set a global variable in Python:

In the example above, x is a global variable that can be accessed by the my_function function. When the function is called, it prints the value of x .

Now let's see what a local variable is in Python.

A local variable is a variable that is defined inside a function and can only be accessed within that function. Local variables have a local scope, which means they are only accessible within the block of code where they are defined.

Here's an example of defining a local variable in Python:

In the example above, y is a local variable that can only be accessed within the my_function function. When the function is called, it prints the value of y .

It's important to note that if you define a local variable with the same name as a global variable, the local variable will take precedence within the function. Here's an example:

In the example above, my_function defines a local variable x with a value of 5 . When the function is called, it prints the value of the local variable, which is 5 . However, the global variable x still has a value of 10 , which is printed when it is called outside of the function.

Dive deep into the topic

  • Array Variables
  • Basic Operations with Variables
  • Boolean Variable Type
  • Dictionaries in Python
  • How to Import Variables from Files
  • How to Print and Format Variables
  • List Variables in Python
  • Numeric Variables
  • Set Type in Python
  • Text and String Variables in Python
  • Tuple Variables in Python

Contribute with us!

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

Profile picture for user almargit

  • 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
  • 105 Funny Things to Do to Make Someone Laugh
  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

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 Numbers, Type Conversion and Mathematics

Python Data Types

In the previous tutorial you learned about Python comments . Now, let's learn about variables and literals in Python.

  • Python Variables

In programming, a variable is a container (storage area) to hold data. For example,

Here, number is a variable storing the value 10 .

  • Assigning values to Variables in Python

As we can see from the above example, we use the assignment operator = to assign a value to a variable.

In the above example, we assigned the value programiz.pro to the site_name variable. Then, we printed out the value assigned to site_name

Note : Python is a type-inferred language, so you don't have to explicitly define the variable type. It automatically knows that programiz.pro is a string and declares the site_name variable as a string.

  • Changing the Value of a Variable in Python

Here, the value of site_name is changed from 'programiz.pro' to 'apple.com' .

Example: Assigning multiple values to multiple variables

If we want to assign the same value to multiple variables at once, we can do this as:

Here, we have assigned the same string value 'programiz.com' to both the variables site1 and site2 .

1. Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase ( A to Z ) or digits ( 0 to 9 ) or an underscore ( _ ) . For example:

2. Create a name that makes sense. For example, vowel makes more sense than v .

3. If you want to create a variable name having two words, use underscore to separate them. For example:

5. Python is case-sensitive. So num and Num are different variables. For example,

6. Avoid using keywords like if, True, class, etc. as variable names.

  • Python Literals

Literals are representations of fixed values in a program. They can be numbers, characters, or strings, etc. For example, 'Hello, World!' , 12 , 23.0 , 'C' , etc.

Literals are often used to assign values to variables or constants. For example,

In the above expression, site_name is a variable, and 'programiz.com' is a literal.

There are different types of literals in Python. Let's discuss some of the commonly used types in detail.

  • Python Numeric Literals

Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types: Integer , Float , and Complex .

1. Integer Literals

Integer literals are numbers without decimal parts. It also consists of negative numbers. For example, 5 , -11 , 0 , 12 , etc.

2. Floating-Point Literals

Floating-point literals are numbers that contain decimal parts.

Just like integers, floating-point numbers can also be both positive and negative. For example, 2.5 , 6.76 , 0.0 , -9.45 , etc.

3. Complex Literals

Complex literals are numbers that represent complex numbers.

Here, numerals are in the form a + bj , where a is real and b is imaginary. For example, 6+9j , 2+3j .

  • Python String Literals

In Python, texts wrapped inside quotation marks are called string literals. .

We can also use single quotes to create strings.

More on Python Literals

There are two boolean literals: True and False .

For example,

Here, True is a boolean literal assigned to is_pass .

Character literals are unicode characters enclosed in a quote. For example,

Here, S is a character literal assigned to some_character .

Python contains one special literal None . We use it to specify a null variable. For example,

Here, we get None as an output as the value variable has no value assigned to it.

Let's see examples of four different collection literals. List, Tuple, Dict, and Set literals.

In the above example, we created a list of fruits , a tuple of numbers , a dictionary of alphabets having values with keys designated to each value and a set of vowels .

To learn more about literal collections, refer to Python Data Types .

Table of Contents

Video: python variables and print().

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 Tutorial

Python Programming

Python Variables

Updated on:  August 31, 2021 | 19 Comments

A variable is a reserved memory area (memory address) to store value . For example, we want to store an employee’s salary. In such a case, we can create a variable and store salary using it. Using that variable name, you can read or modify the salary amount.

In other words, a variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python.

A variable can be either mutable or immutable . If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable. We will learn the difference between mutable and immutable types in the later section of this article.

Also, Solve :

  • Python variables and data type Quiz
  • Basic Python exercise for beginners

Table of contents

Creating a variable, changing the value of a variable, integer variable, float variable, complex type, string variable, list type variable, get the data type of variable, delete a variable, variable’s case-sensitive, assigning a value to a constant in python, rules and naming convention for variables and constants, assigning a single value to multiple variables, assigning multiple values to multiple variables, local variable, global variable, object reference, unpack a collection into a variable.

Python programming language is dynamically typed, so there is no need to declare a variable before using it or declare the data type of variable like in other programming languages. The declaration happens automatically when we assign a value to the variable.

Creating a variable and assigning a value

We can assign a value to the variable at that time variable is created. We can use the assignment operator = to assign a value to a variable.

The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value.

In the above example, “John”, 25, 25800.60 are values that are assigned to name , age , and salary respectively.

Many programming languages are statically typed languages where the variable is initially declared with a specific type, and during its lifetime, it must always have that type.

But in Python, variables are dynamically typed  and not subject to the data type restriction. A variable may be assigned to a value of  one type , and then later, we can also re-assigned a value of a different type . Let’s see the example.

Create Number, String, List variables

We can create different types of variables as per our requirements. Let’s see each one by one.

A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values.

The  int is a data type that returns integer type values (signed integers); they are also called  ints or integers . The integer value can be positive or negative without a decimal point.

Note : We used the built-in Python method type() to check the variable type.

Floats are the values with the decimal point dividing the integer and the fractional parts of the number.  Use float data type to store decimal values.

In the above example, the variable salary assigned to value 10800.55, which is a float value.

The complex is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values.

In Python, a string is a set of characters  represented in quotation marks. Python allows us to define a string in either pair of  single  or  double quotation marks. For example, to store a person’s name we can use a string type.

To retrieve a piece of string from a given string, we can use to slice operator [] or [:] . Slicing provides us the subset of a string with an index starting from index 0 to index end-1.

To concatenate the string, we can use  the addition (+) operator.

If we want to represent  a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact.

Read : Complete Guide on Python lists

The list can be accessed in two ways, either positive or negative index.  The list has the following characteristics:

  • In the list insertion order of elements is preserved.
  • Heterogeneous (all types of data types int , float , string ) elements are allowed.
  • Duplicates elements are permitted.
  • The list is mutable(can change).
  • Growable in nature means based on our requirement, we can increase or decrease the list’s size.
  • List elements should be enclosed within square brackets [] .

No matter what is stored in a variable (object), a variable can be any type like int , float , str , list , tuple , dict , etc. There is a built-in function called type() to get the data type of any variable.

The type() function has a simple and straightforward syntax.

Syntax of type() :

If we want to get the name of the datatype only as output, then we can use the __name__ attribute along with the type() function. See the following example where __name__ attribute is used.

Use the del keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector.

Now, let’s delete var1 and try to access it again.

Python is a case-sensitive language. If we define a variable with names a = 100 and A =200 then, Python differentiates between a and A . These variables are treated as two different variables (or objects).

Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is  not applicable . By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it.

 Example

It is just convention, but we can change the value of MAX_VALUE variable.

As we see earlier, in the case of Python, the constant concept is not applicable. But if we still want to implement it, we can do it using the following way.

The declaration and assignment of constant in Python done with the module. Module means Python file ( .py ) which contains variables, functions, and packages.

So let’s create two modules, constant.py  and main.py , respectively.

  • In the constant.py file, we will declare two constant variables,  PI and TOTAL_AREA .
  • import constant module In main.py file.

To create a constant module write the below code in the constant.py file.

Constants are declared with uppercase later variables and separating the words with an underscore.

Create a  main.py  and write the below code in it.

Note : Constant concept is not available in Python. By convention, we define constants in an uppercase letter to differentiate from variables. But it does not prevent reassignment, which means we can change the value of a constant variable.

A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name.

There are some rules to define variables in Python.

In Python, there are some conventions and rules to define variables and constants that should follow.

Rule 1 : The name of the variable and constant should have a combination of letters, digits, and underscore symbols.

  • Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z)
  • Digits(0 to 9)
  • Underscore symbol (_)

Example 

Rule 2 : The variable name and constant name should make sense.

Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful.

It above example variable x does not make more sense, but student_name  is a meaningful variable.

Rule 3: Don’t’ use special symbols in a variable name

For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error

Rule 4:  Variable and constant should not start with digit letters.

You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example.

Here Python will generate a syntax error at 1studnet . instead of this, you can declare a variable like studnet_1 = "Jessa"

Rule 5:  Identifiers are case sensitive.

Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables total , Total , TOTAL .

Rule 6:  To declare constant should use capital letters.

Rule 6: Use an underscore symbol for separating the words in a variable name

If we want to declare variable and constant names having two words, use an underscore symbol for separating the words.

Multiple assignments

In Python, there is no restriction to declare a variable before using it in the program. Python allows us to create a variable as and when required.

We can do multiple assignments in two ways, either by assigning a single value to multiple variables  or assigning  multiple values to multiple variables .

we can assign a single value to multiple variables simultaneously using the assignment operator = .

Now, let’s create an example to assign the single value 10 to all three variables a , b , and c .

In the above example, two integer values 10 and 70 are assigned to variables roll_no and marks , respectively, and string literal, “Jessa,” is assigned to the variable name .

Variable scope

Scope : The scope of a variable refers to the places where we can access a variable.

Depending on the scope, the variable can categorize into two types  local variable and the global variable.

A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error.

In the above example, we created a function with the name test1 . Inside it, we created a local variable price. Similarly, we created another function with the name test2 and tried to access price, but we got an error "price is not defined" because its scope is limited to function test1() . This error occurs because we cannot access the local variable from outside the code block.

A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.

In the above example, we created a global variable price and tried to access it in test1 and test2 . In return, we got the same value because the global variable is accessible in the entire file.

Note : You must declare the global variable outside function.

Object/Variable identity and references

In Python, whenever we create an object, a number is given to it and uniquely identifies it. This number is nothing but a memory address of a variable’s value. Once the object is created, the identity of that object never changes.

No two objects will have the same identifier. The Object is for eligible garbage collection when deleted. Python has a built-in function id() to get the memory address of a variable.

For example, consider a library with many books (memory addresses) and many students (objects). At the beginning(when we start The Python program), all books are available. When a new student comes to the library (a new object created), the librarian gives him a book. Every book has a unique number (identity), and that id number tells us which book is delivered to the student (object)

It returns the same address location because both variables share the same value. But if we assign m to some different value, it points to a different object with a different identity.

See the following example

For m = 500 , Python created an integer object with the value 500 and set m as a reference to it. Similarly, n is assigned to an integer object with the value 400 and sets n as a reference to it. Both variables have different identities.

In Python, when we assign a value to a variable, we create an object and reference it.

For example, a=10 , here, an object with the value  10 is created in memory, and reference a now points to the memory address where the object is stored.

Suppose we created a=10 , b=10 , and  c=10 , the value of the three variables is the same. Instead of creating three objects, Python creates only one object as  10  with references such as  a , b , c .

We can access the memory addresses of these variables using the id() method. a , b refers to the same address  in memory, and c , d , e refers to the same address. See the following example for more details.

Here, an object in memory initialized with the value 10 and reference added to it, the reference count increments by ‘1’.

When Python executes the next statement that is b=10 , since it is the same value 10, a new object will not be created because the same object in memory with value 10 available, so it has created another reference, b . Now, the reference count for value 10 is ‘2’.

Again for  c=20 , a new object is created with reference ‘c’ since it has a unique value (20). Similarly, for d , and e  new objects will not be created because the object ’20’ already available. Now, only the reference count will be incremented.

We can check the reference counts of every object by using the getrefcount function of a  sys module. This function takes the object as an input and returns the number of references.

We can pass variable, name, value, function, class as an input to getrefcount() and in return, it will give a reference count for a given object.

See the following image for more details.

Python object id references

In the above picture, a , b pointing to the same memory address location (i.e., 140722211837248), and c , d , e pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2 and 3 respectively.

  • In Python, we can create a tuple (or list) by packing a group of variables.
  • Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing.

Here a , b , c , d  are packed in the tuple tuple1 .

Tuple unpacking  is the reverse operation of tuple packing . We can unpack tuple and assign tuple values to different variables.

Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError .

Also, See :

  • Class Variables
  • Instance variables

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

different types of variable assignment in python

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

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
  • Online Python Code Editor
  • 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

Different Types of Variables in Python with Examples

Types of variables in python.

Variable Types in Python are just reserved memory spaces for storing values. This means that when you create a variable, you reserve memory space.

Python is entirely object-oriented and is not “statically typed.” You do not need to declare variables or declare their type before utilizing them.

Variable TypeDescriptionExample
IntegerStores whole numbers without decimal pointsage = 30
FloatStores decimal numberspi = 3.14
StringStores sequences of charactersname = “Mary”
BooleanStores either True or Falseis_valid = True
Stores an ordered collection of itemsnumbers = [1, 2, 3, 4]
Stores an ordered collection of items (immutable)point = (5, 10)
Stores key-value pairsperson = {“name”: “Mary”, “age”: 30}
Stores an unordered collection of unique itemsunique_numbers = {1, 2, 3, 4}

Assigning Values to Variables

The name of the variable is the operand to the left of the = operator, and the value stored in the variable is the operand to the right of the = operator.

This causes the following to happen:

Multiple Assignment

For instance:

For example:

Different Types of Variables in Python

Here are some common types of variables:

1. Python Numbers

The del statement’s syntax is:

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

2. Python Strings

Python strings are a data type used to represent sequences of characters. They are enclosed in single (‘ ‘) or double (” “) quotes.

Also, in Python, you can extract parts of strings using the slice operator ([] and [:]) and index positions that range from 0 to -1.

3. Python Lists

4. python tuples.

However, tuples are immutable, meaning their values cannot be changed once assigned.

This leads to the following:

5. Python Dictionary

How to check the type of variable in python.

Here’s an example of how to use the type() function to check the type of a variable:

In summary, we explored the Types of Variables in Python which is a reserved memory space. Also, we learned how to assign variables, including multiple Assignments .

1 thought on “Different Types of Variables in Python with Examples”

#goodstudent #python

Leave a Comment Cancel reply

  • Conditionals  > 

In Python, Boolean values are stored in the bool data type. Variables of the bool data type can only store one of two values, True or False . So, a Boolean value is really the simplest data value we can imagine - it is a single binary bit representing a value of True or False .

To create a Boolean variable in Python, we can simply assign those values to a variable in an assignment statement:

When we execute that code, we’ll see the following output:

In Python, we use the keywords True and False to represent Boolean values. In Python, it is very important to make sure these values are capitalized, otherwise the program will not work properly. Also, since these are keywords and not strings, we don’t need to put them in quotation marks.

Converting Between Data Types

Python includes the special bool() function, which can be used to convert any data type into a Boolean value. The bool() function follows these rules to determine what to return:

  • If the input is the value False , the value 0 , the value None , or anything with 0 length, including the empty string, it will return False .
  • Otherwise, for all other values it will return True .

Let’s look at a couple of quick examples. First, let’s try to convert the strings "True" and "False" to their Boolean equivalents:

When this code is executed, we’ll see this output:

This seems a bit strange, since the string "False" ended up creating the Boolean value True . However, if we look at the rules above, since the string "False" has a length greater than 1, and it is not any of the special values listed above, it should always result in the Boolean value True .

In this example, we can check a couple of special values using the bool() function:

In this case, we’ll see the following output:

Here, we see that the value 0 , as well as the empty string "" , both result in a value of False . However, the value 1 is True , since it is a non-zero value.

In practice, we won’t use the bool() function directly very often. Instead, if we want to determine if a user inputs a True or False value, we can just use one of the Boolean comparators that we’ll see later in this lab.

Last modified by: Russell Feldhausen Jun 27, 2024

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

How do I pass a variable by reference?

I wrote this class for testing:

When I tried creating an instance, the output was Original . So it seems like parameters in Python are passed by value. Is that correct? How can I modify the code to get the effect of pass-by-reference, so that the output is Changed ?

Sometimes people are surprised that code like x = 1 , where x is a parameter name, doesn't impact on the caller's argument, but code like x[0] = 1 does. This happens because item assignment and slice assignment are ways to mutate an existing object, rather than reassign a variable, despite the = syntax. See Why can a function modify some arguments as perceived by the caller, but not others? for details.

See also What's the difference between passing by reference vs. passing by value? for important, language-agnostic terminology discussion.

  • parameter-passing
  • pass-by-reference

Karl Knechtel's user avatar

  • 32 For a short explanation/clarification see the first answer to this stackoverflow question . As strings are immutable, they won't be changed and a new variable will be created, thus the "outer" variable still has the same value. –  PhilS Commented Jun 12, 2009 at 10:35
  • 11 The code in BlairConrad's answer is good, but the explanation provided by DavidCournapeau and DarenThomas is correct. –  Ethan Furman Commented Jan 7, 2012 at 6:47
  • 79 Before reading the selected answer, please consider reading this short text Other languages have "variables", Python has "names" . Think about "names" and "objects" instead of "variables" and "references" and you should avoid a lot of similar problems. –  lqc Commented Nov 15, 2012 at 0:39
  • 4 Working link: Other languages have "variables", Python has "names" –  Abraham Sangha Commented Apr 22, 2020 at 23:30
  • 13 New official how of Iqc's link: david.goodger.org/projects/pycon/2007/idiomatic/… –  Ray Hulha Commented Jun 9, 2020 at 19:56

42 Answers 42

Arguments are passed by assignment . The rationale behind this is twofold:

  • the parameter passed in is actually a reference to an object (but the reference is passed by value)
  • some data types are mutable, but others aren't

If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.

If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.

To make it even more clear, let's have some examples.

List - a mutable type

Let's try to modify the list that was passed to a method:

Since the parameter passed in is a reference to outer_list , not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.

Now let's see what happens when we try to change the reference that was passed in as a parameter:

Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed.

String - an immutable type

It's immutable, so there's nothing we can do to change the contents of the string

Now, let's try to change the reference

Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed.

I hope this clears things up a little.

EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.

How do we get around this?

As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:

If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:

Although this seems a little cumbersome.

random_user's user avatar

  • 211 Then the same is in C, when you pass "by reference" you're actually passing by value the reference... Define "by reference" :P –  Andrea Ambu Commented Jun 12, 2009 at 11:52
  • 128 I'm not sure I understand your terms. I've been out of the C game for a while, but back when I was in it, there was no "pass by reference" - you could pass things, and it was always pass by value, so whatever was in the parameter list was copied. But sometimes the thing was a pointer, which one could follow to the piece of memory (primitive, array, struct, whatever), but you couldn't change the pointer that was copied from the outer scope - when you were done with the function, the original pointer still pointed to the same address. C++ introduced references, which behaved differently. –  Blair Conrad Commented Jun 12, 2009 at 12:09
  • 47 @Zac Bowling I don't really get how what you're saying is relevant, in a practical sense, to this answer. If a Python newcomer wanted to know about passing by ref/val, then the takeaway from this answer is: 1- You can use the reference that a function receives as its arguments, to modify the 'outside' value of a variable, as long as you don't reassign the parameter to refer to a new object. 2- Assigning to an immutable type will always create a new object, which breaks the reference that you had to the outside variable. –  Cam Jackson Commented Sep 8, 2011 at 23:50
  • 16 @CamJackson, you need a better example - numbers are also immutable objects in Python. Besides, wouldn't it be true to say that any assignment without subscripting on the left side of the equals will reassign the name to a new object whether it is immutable or not? def Foo(alist): alist = [1,2,3] will not modify the contents of the list from the callers perspective. –  Mark Ransom Commented Nov 15, 2011 at 16:46
  • 74 -1. The code shown is good, the explanation as to how is completely wrong. See the answers by DavidCournapeau or DarenThomas for correct explanations as to why. –  Ethan Furman Commented Jan 7, 2012 at 6:41

The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:

You believe that a is a memory location that stores the value 1 , then is updated to store the value 2 . That's not how things work in Python. Rather, a starts as a reference to an object with the value 1 , then gets reassigned as a reference to an object with the value 2 . Those two objects may continue to coexist even though a doesn't refer to the first one anymore; in fact they may be shared by any number of other references within the program.

When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:

self.variable is a reference to the string object 'Original' . When you call Change you create a second reference var to the object. Inside the function you reassign the reference var to a different string object 'Changed' , but the reference self.variable is separate and does not change.

The only way around this is to pass a mutable object. Because both references refer to the same object, any changes to the object are reflected in both places.

Mark Ransom's user avatar

  • 133 Good succinct explanation. Your paragraph "When you call a function..." is one of the best explanations I've heard of the rather cryptic phrase that 'Python function parameters are references, passed by value.' I think if you understand that paragraph alone, everything else kind of just makes sense and flows as a logical conclusion from there. Then you just have to be aware of when you're creating a new object and when you're modifying an existing one. –  Cam Jackson Commented Nov 16, 2011 at 0:03
  • 4 But how can you reassign the reference? I thought you can't change the address of 'var' but that your string "Changed" was now going to be stored in the 'var' memory address. Your description makes it seem like "Changed" and "Original" belong to different places in memory instead and you just switch 'var' to a different address. Is that correct? –  Kashif Commented May 7, 2012 at 1:10
  • 11 @Glassjawed, I think you're getting it. "Changed" and "Original" are two different string objects at different memory addresses and 'var' changes from pointing to one to pointing to the other. –  Mark Ransom Commented May 7, 2012 at 1:46
  • 2 Function calls do not create new references - use the id function inside and outside of the function to confirm that. The difference is what happens to the object when you attempt to change it inside the function. –  Tony Suffolk 66 Commented Mar 10, 2018 at 10:55
  • 5 @TonySuffolk66 id gives the identity of the object referenced, not the reference itself. –  Mark Ransom Commented Mar 10, 2018 at 14:24

enter image description here

  • 10 Thanks for the update, much better! What confuses most people is assignment to a subscription; e.g. B[0] = 2 , vs. direct assignment, B = 2 . –  Martijn Pieters Commented May 25, 2016 at 16:32
  • 15 "A is assigned to B." Is that not ambiguous? I think in ordinary English that can mean either A=B or B=A . –  Hatshepsut Commented Jul 4, 2016 at 23:06
  • I do like the visual representation, but still misses the point of mutable vs immutable which makes the right leg moot since there will be no append available. (still got an upvote for the visual rep though) :) –  Madivad Commented Jul 19, 2016 at 12:40
  • What do you mean by B is modified in-place?B is not an object –  Abhinav Commented Oct 20, 2019 at 3:57
  • 1 "Something else is assigned to B" should be "B is assigned to something else". Names are assigned to values, not the other way around. Names refer to values, values don't know what names they have. –  timgeb Commented Feb 28, 2022 at 9:11

It is neither pass-by-value or pass-by-reference - it is call-by-object. See this, by Fredrik Lundh:

Call By Object

Here is a significant quote:

"...variables [names] are not objects; they cannot be denoted by other variables or referred to by objects."

In your example, when the Change method is called--a namespace is created for it; and var becomes a name, within that namespace, for the string object 'Original' . That object then has a name in two namespaces. Next, var = 'Changed' binds var to a new string object, and thus the method's namespace forgets about 'Original' . Finally, that namespace is forgotten, and the string 'Changed' along with it.

Peter Mortensen's user avatar

  • 25 I find it hard to buy. To me is just as Java, the parameters are pointers to objects in memory, and those pointers are passed via the stack, or registers. –  Luciano Commented Dec 13, 2011 at 1:25
  • 10 This is not like java. One of the case where it is not the same is immutable objects. Think about the trivial function lambda x: x. Apply this for x = [1, 2, 3] and x = (1, 2, 3). In the first case, the returned value will be a copy of the input, and identical in the second case. –  David Cournapeau Commented Dec 14, 2011 at 1:53
  • 34 No, it's exactly like Java's semantics for objects. I'm not sure what you mean by "In the first case, the returned value will be a copy of the input, and identical in the second case." but that statement seems to be plainly incorrect. –  Mike Graham Commented Nov 14, 2012 at 20:58
  • 28 It is exactly the same as in Java. Object references are passed by value. Anyone who thinks differently should attach the Python code for a swap function that can swap two references, like this: a = [42] ; b = 'Hello'; swap(a, b) # Now a is 'Hello', b is [42] –  cayhorstmann Commented Dec 20, 2012 at 3:42
  • 28 It is exactly the same as Java when you pass objects in Java. However, Java also have primitives, which are passed by copying the value of the primitive. Thus they differ in that case. –  Claudiu Commented Jul 17, 2013 at 18:59

Think of stuff being passed by assignment instead of by reference/by value. That way, it is always clear, what is happening as long as you understand what happens during the normal assignment.

So, when passing a list to a function/method, the list is assigned to the parameter name. Appending to the list will result in the list being modified. Reassigning the list inside the function will not change the original list, since:

Since immutable types cannot be modified, they seem like being passed by value - passing an int into a function means assigning the int to the function's parameter. You can only ever reassign that, but it won't change the original variables value.

MurugananthamS's user avatar

  • 11 At first glance this answer seems to sidestep the original question. After a second read I've come to realize that this makes the matter quite clear. A good follow up to this "name assignment" concept may be found here: Code Like a Pythonista: Idiomatic Python –  Christian Groleau Commented Nov 22, 2017 at 21:45
  • 1 So, can it be summarized as: assigning an immutable type is essentially re-assigning it, because assigning a type that can't be modified is meaningless? –  Egret Commented Nov 17, 2023 at 4:29

There are no variables in Python

The key to understanding parameter passing is to stop thinking about "variables". There are names and objects in Python and together they appear like variables, but it is useful to always distinguish the three.

  • Python has names and objects.
  • Assignment binds a name to an object.
  • Passing an argument into a function also binds a name (the parameter name of the function) to an object.

That is all there is to it. Mutability is irrelevant to this question.

This binds the name a to an object of type integer that holds the value 1.

This binds the name b to the same object that the name x is currently bound to. Afterward, the name b has nothing to do with the name x anymore.

See sections 3.1 and 4.2 in the Python 3 language reference.

How to read the example in the question

In the code shown in the question, the statement self.Change(self.variable) binds the name var (in the scope of function Change ) to the object that holds the value 'Original' and the assignment var = 'Changed' (in the body of function Change ) assigns that same name again: to some other object (that happens to hold a string as well but could have been something else entirely).

How to pass by reference

So if the thing you want to change is a mutable object, there is no problem, as everything is effectively passed by reference.

If it is an immutable object (e.g. a bool, number, string), the way to go is to wrap it in a mutable object. The quick-and-dirty solution for this is a one-element list (instead of self.variable , pass [self.variable] and in the function modify var[0] ). The more pythonic approach would be to introduce a trivial, one-attribute class. The function receives an instance of the class and manipulates the attribute.

faressalem's user avatar

  • 56 "Python has no variables" is a silly and confusing slogan, and I really wish people would stop saying it... :( The rest of this answer is good! –  Ned Batchelder Commented Jun 23, 2014 at 21:53
  • 23 It may be shocking, but it is not silly. And I don't think it is confusing either: It hopefully opens up the recipient's mind for the explanation that is coming and puts her in a useful "I wonder what they have instead of variables" attitude. (Yes, your mileage may vary.) –  Lutz Prechelt Commented Jun 25, 2014 at 7:30
  • 28 would you also say that Javascript has no variables? They work the same as Python's. Also, Java, Ruby, PHP, .... I think a better teaching technique is, "Python's variables work differently than C's." –  Ned Batchelder Commented Jun 25, 2014 at 11:09
  • 14 Yes, Java has variables. So does Python, and JavaScript, Ruby, PHP, etc. You wouldn't say in Java that int declares a variable, but Integer does not. They both declare variables. The Integer variable is an object, the int variable is a primitive. As an example, you demonstrated how your variables work by showing a = 1; b = a; a++ # doesn't modify b . That's exactly true in Python also (using += 1 since there is no ++ in Python)! –  Ned Batchelder Commented Oct 29, 2014 at 16:29
  • 7 The concept of "variable" is complex and often vague: A variable is a container for a value, identified by a name. In Python, the values are objects, the containers are objects (see the problem?) and the names are actually separate things. I believe it is much tougher to get an accurate understanding of variables in this manner. The names-and-objects explanation appears more difficult, but is actually simpler. –  Lutz Prechelt Commented Oct 9, 2015 at 10:51

Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: https://web.archive.org/web/20201111195827/http://effbot.org/zone/call-by-object.htm

Objects are allocated on the heap and pointers to them can be passed around anywhere.

When you make an assignment such as x = 1000 , a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.

When you update "x" with x = 2000 , a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).

When you do a new assignment such as y = x , a new dictionary entry "y" is created that points to the same object as the entry for "x".

Objects like strings and integers are immutable . This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.

Objects like lists are mutable . This means that the contents of the object can be changed by anything pointing to the object. For example, x = []; y = x; x.append(10); print y will print [10] . The empty list was created. Both "x" and "y" point to the same list. The append method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).

Hope that clarifies the issue for you.

Indradhanush Gupta's user avatar

  • 6 I really appreciate learning about this from a developer. Is it true that the id() function returns the pointer's (object reference's) value, as pepr's answer suggests? –  Honest Abe Commented Jan 13, 2014 at 22:21
  • 7 @HonestAbe Yes, in CPython the id() returns the address. But in other pythons such as PyPy and Jython, the id() is just a unique object identifier. –  Raymond Hettinger Commented Jan 14, 2014 at 9:03
  • The dictionary is a reasonable mental model, and pretty accurate for 2.x; but in 3.x, local variables have optimized storage that doesn't work like a dictionary, and the locals() function needs to create a dict on the fly. –  Karl Knechtel Commented Jul 12, 2023 at 16:36

Technically, Python always uses pass by reference values . I am going to repeat my other answer to support my statement.

Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. Any variable is the name bound to the reference value. Always.

You can think about a reference value as the address of the target object. The address is automatically dereferenced when used. This way, working with the reference value, it seems you work directly with the target object. But there always is a reference in between, one step more to jump to the target.

Here is the example that proves that Python uses passing by reference:

Illustrated example of passing the argument

If the argument was passed by value, the outer lst could not be modified. The green are the target objects (the black is the value stored inside, the red is the object type), the yellow is the memory with the reference value inside -- drawn as the arrow. The blue solid arrow is the reference value that was passed to the function (via the dashed blue arrow path). The ugly dark yellow is the internal dictionary. (It actually could be drawn also as a green ellipse. The colour and the shape only says it is internal.)

You can use the id() built-in function to learn what the reference value is (that is, the address of the target object).

In compiled languages, a variable is a memory space that is able to capture the value of the type. In Python, a variable is a name (captured internally as a string) bound to the reference variable that holds the reference value to the target object. The name of the variable is the key in the internal dictionary, the value part of that dictionary item stores the reference value to the target.

Reference values are hidden in Python. There isn't any explicit user type for storing the reference value. However, you can use a list element (or element in any other suitable container type) as the reference variable, because all containers do store the elements also as references to the target objects. In other words, elements are actually not contained inside the container -- only the references to elements are.

Community's user avatar

  • 47 Inventing new terminology (such as "pass by reference value" or "call by object" is not helpful). "Call by (value|reference|name)" are standard terms. "reference" is a standard term. Passing references by value accurately describes the behavior of Python, Java, and a host of other languages, using standard terminology. –  cayhorstmann Commented Dec 20, 2012 at 3:54
  • 6 @cayhorstmann: The problem is that Python variable has not the same terminology meaning as in other languages. This way, call by reference does not fit well here. Also, how do you exactly define the term reference ? Informally, the Python way could be easily described as passing the address of the object. But it does not fit with a potentially distributed implementation of Python. –  pepr Commented Dec 20, 2012 at 8:54
  • 1 I like this answer, but you might consider if the example is really helping or hurting the flow. Also, if you replaced 'reference value' with 'object reference' you would be using terminology that we could consider 'official', as seen here: Defining Functions –  Honest Abe Commented Jan 13, 2014 at 22:10
  • 1 Well, but the official says... " arguments are passed using call by value (where the value is always an object reference , not the value of the object). " This way, you may be tempted to substitute it textually as ... arguments are passed using call by reference , which is a bit confusing beacuse it is not true. The confusion is caused by a bit more complex situation where none of the classical terms fits perfectly. I did not find any simpler example that would illustrate the behaviour. –  pepr Commented Jan 14, 2014 at 23:31
  • 2 There is a footnote indicated at the end of that quote, which reads: "Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it..." I agree with you that confusion is caused by trying to fit terminology established with other languages. Semantics aside, the things that need to be understood are: dictionaries / namespaces, name binding operations and the relationship of name→pointer→object (as you already know). –  Honest Abe Commented Jan 16, 2014 at 6:28

A simple trick I normally use is to just wrap it in a list:

(Yeah I know this can be inconvenient, but sometimes it is simple enough to do this.)

AmanicA's user avatar

  • 9 Nice. To pass by ref, wrap in [ ]'s. –  Justas Commented Feb 1, 2015 at 5:49

You got some really good answers here.

Alex L's user avatar

  • 3 yea, however if you do x = [ 2, 4, 4, 5, 5], y = x, X[0] = 1 , print x # [1, 4 ,4, 5, 5] print y # [1, 4, 4, 5, 5] –  laycat Commented Jun 29, 2014 at 3:37
  • X[0] or x[0] ? don't get it –  pippo1980 Commented Aug 1, 2021 at 7:16

In this case the variable titled var in the method Change is assigned a reference to self.variable , and you immediately assign a string to var . It's no longer pointing to self.variable . The following code snippet shows what would happen if you modify the data structure pointed to by var and self.variable , in this case a list:

I'm sure someone else could clarify this further.

Mike Mazur's user avatar

Python’s pass-by-assignment scheme isn’t quite the same as C++’s reference parameters option, but it turns out to be very similar to the argument-passing model of the C language (and others) in practice:

  • Immutable arguments are effectively passed “ by value .” Objects such as integers and strings are passed by object reference instead of by copying, but because you can’t change immutable objects in place anyhow, the effect is much like making a copy.
  • Mutable arguments are effectively passed “ by pointer .” Objects such as lists and dictionaries are also passed by object reference, which is similar to the way C passes arrays as pointers—mutable objects can be changed in place in the function, much like C arrays.

ajknzhol's user avatar

There are a lot of insights in answers here, but I think an additional point is not clearly mentioned here explicitly. Quoting from Python documentation What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’. Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Even when passing a mutable object to a function this still applies. And to me it clearly explains the reason for the difference in behavior between assigning to the object and operating on the object in the function.

The assignment to an global variable that is not declared global therefore creates a new local object and breaks the link to the original object.

Joop's user avatar

As you can state you need to have a mutable object, but let me suggest you to check over the global variables as they can help you or even solve this kind of issue!

http://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

John Smith's user avatar

  • 5 I was tempted to post a similar response- the original questioner may not have known that what he wanted was in fact to use a global variable, shared among functions. Here's the link I would have shared: stackoverflow.com/questions/423379/… In answer to @Tim, Stack Overflow is not only a question and answer site, it's a vast repository of reference knowledge that only gets stronger and more nuanced- much like an active wiki- with more input. –  Max P Magee Commented Jun 30, 2014 at 18:39

Here is the simple (I hope) explanation of the concept pass by object used in Python. Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:

The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function change_me will try to do something like:

which obviously will not change the object passed to the function. If the function looked like this:

Then the call would result in:

which obviously will change the object. This answer explains it well.

  • 3 The problem is that the assignment does something else than you expect. The list = [1, 2, 3] causes reusing the list name for something else and forgeting the originally passed object. However, you can try list[:] = [1, 2, 3] (by the way list is wrong name for a variable. Thinking about [0, 1] = [1, 2, 3] is a complete nonsense. Anyway, what do you think means the object itself is passed ? What is copied to the function in your opinion? –  pepr Commented Oct 3, 2012 at 20:46
  • @pepr objects aren't literals. They are objects. The only way to talk about them is giving them some names. That's why it's so simple once you grasp it, but enormously complicated to explain. :-) –  Veky Commented May 9, 2014 at 9:10
  • @Veky: I am aware of that. Anyway, the list literal is converted to the list object. Actually, any object in Python can exist without a name, and it can be used even when not given any name. And you can think about them as about anonymous objects. Think about objects being the elements of a lists. They need not a name. You can access them through indexing of or iterating through the list. Anyway, I insist on [0, 1] = [1, 2, 3] is simply a bad example. There is nothing like that in Python. –  pepr Commented May 12, 2014 at 11:05
  • @pepr: I don't necessarily mean Python-definition names, just ordinary names. Of course alist[2] counts as a name of a third element of alist. But I think I misunderstood what your problem was. :-) –  Veky Commented May 12, 2014 at 12:35
  • Argh. My English is obviously much worse than my Python. :-) I'll try just once more. I just said you have to give object some names just to talk about them. By that "names" I didn't mean "names as defined by Python". I know Python mechanisms, don't worry. –  Veky Commented May 15, 2014 at 5:20

Aside from all the great explanations on how this stuff works in Python, I don't see a simple suggestion for the problem. As you seem to do create objects and instances, the Pythonic way of handling instance variables and changing them is the following:

In instance methods, you normally refer to self to access instance attributes. It is normal to set instance attributes in __init__ and read or change them in instance methods. That is also why you pass self as the first argument to def Change .

Another solution would be to create a static method like this:

Dolf Andringa's user avatar

I used the following method to quickly convert some Fortran code to Python. True, it's not pass by reference as the original question was posed, but it is a simple workaround in some cases.

Brad Porter's user avatar

  • Yes, this solves the 'pass by reference' in my use case as well. I have a function that basically cleans up values in a dict and then returns the dict . However, while cleaning up it may become apparent a rebuild of a part of the system is required. Therefore, the function must not only return the cleaned dict but also be able to signal the rebuild. I tried to pass a bool by reference, but ofc that doesn't work. Figuring out how to solve this, I found your solution (basically returning a tuple) to work best while also not being a hack/workaround at all (IMHO). –  kasimir Commented May 1, 2020 at 16:08

To simulate passing an object by reference, wrap it in a one-item list:

Assigning to an element of the list mutates the list rather than reassigning a name. Since the list itself has reference semantics, the change is reflected in the caller.

itmuckel's user avatar

  • p is reference to a mutable list object which in turn stores the object obj . The reference 'p', gets passed into changeRef . Inside changeRef , a new reference is created (the new reference is called ref ) that points to the same list object that p points to. But because lists are mutable, changes to the list are visible by both references. In this case, you used the ref reference to change the object at index 0 so that it subsequently stores the PassByReference('Michael') object. The change to the list object was done using ref but this change is visible to p . –  Minh Tran Commented Oct 20, 2018 at 3:19
  • So now, the references p and ref point to a list object that stores the single object, PassByReference('Michael') . So it follows that p[0].name returns Michael . Of course, ref has now gone out of scope and may be garbage collected but all the same. –  Minh Tran Commented Oct 20, 2018 at 3:22
  • 1 You have not changed the private instance variable, name , of the original PassByReference object associated with the reference obj , though. In fact, obj.name will return Peter . The aforementioned comments assumes the definition Mark Ransom gave. –  Minh Tran Commented Oct 20, 2018 at 3:25
  • 1 Point being, I don't agree that it's a hack (which I take to mean to refer to something that works but for reasons unknown, untested, or unintended by the implementer). You simply replaced one PassByReference object with another PassByReference object in your list and referred to the latter of the two objects. –  Minh Tran Commented Oct 20, 2018 at 3:32

Since it seems to be nowhere mentioned an approach to simulate references as known from e.g. C++ is to use an "update" function and pass that instead of the actual variable (or rather, "name"):

This is mostly useful for "out-only references" or in a situation with multiple threads / processes (by making the update function thread / multiprocessing safe).

Obviously the above does not allow reading the value, only updating it.

Daniel Jour's user avatar

  • I think it would be better to have a separate, language-agnostic Q&A for strategies for emulating pass-by-reference. –  Karl Knechtel Commented Jul 12, 2023 at 17:08

Since dictionaries are passed by reference, you can use a dict variable to store any referenced values inside it.

Liakos's user avatar

Given the way Python handles values and references to them, the only way you can reference an arbitrary instance attribute is by name:

In real code you would, of course, add error checking on the dict lookup.

mARK bLOORE's user avatar

Since your example happens to be object-oriented, you could make the following change to achieve a similar result:

Jesse Hogan's user avatar

  • 2 Although this works. It is not pass by reference. It is 'pass by object reference'. –  Bishwas Mishra Commented Mar 14, 2018 at 11:48

You can merely use an empty class as an instance to store reference objects because internally object attributes are stored in an instance dictionary. See the example.

sergzach's user avatar

While pass by reference is nothing that fits well into Python and should be rarely used, there are some workarounds that actually can work to get the object currently assigned to a local variable or even reassign a local variable from inside of a called function.

The basic idea is to have a function that can do that access and can be passed as object into other functions or stored in a class.

One way is to use global (for global variables) or nonlocal (for local variables in a function) in a wrapper function.

The same idea works for reading and del eting a variable.

For just reading, there is even a shorter way of just using lambda: x which returns a callable that when called returns the current value of x. This is somewhat like "call by name" used in languages in the distant past.

Passing 3 wrappers to access a variable is a bit unwieldy so those can be wrapped into a class that has a proxy attribute:

Pythons "reflection" support makes it possible to get a object that is capable of reassigning a name/variable in a given scope without defining functions explicitly in that scope:

Here the ByRef class wraps a dictionary access. So attribute access to wrapped is translated to a item access in the passed dictionary. By passing the result of the builtin locals and the name of a local variable, this ends up accessing a local variable. The Python documentation as of 3.5 advises that changing the dictionary might not work, but it seems to work for me.

textshell's user avatar

  • Re "The Python documentation as of 3.5" : Can you add the reference? (But **** without **** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) –  Peter Mortensen Commented Feb 18, 2023 at 20:29

Pass-by-reference in Python is quite different from the concept of pass by reference in C++/Java.

Java and C#: primitive types (including string) pass by value (copy). A reference type is passed by reference (address copy), so all changes made in the parameter in the called function are visible to the caller.

C++: Both pass-by-reference or pass-by-value are allowed. If a parameter is passed by reference, you can either modify it or not depending upon whether the parameter was passed as const or not. However, const or not, the parameter maintains the reference to the object and reference cannot be assigned to point to a different object within the called function.

Python: Python is “pass-by-object-reference”, of which it is often said: “Object references are passed by value.” ( read here ). Both the caller and the function refer to the same object, but the parameter in the function is a new variable which is just holding a copy of the object in the caller. Like C++, a parameter can be either modified or not in function. This depends upon the type of object passed. For example, an immutable object type cannot be modified in the called function whereas a mutable object can be either updated or re-initialized.

A crucial difference between updating or reassigning/re-initializing the mutable variable is that updated value gets reflected back in the called function whereas the reinitialized value does not. The scope of any assignment of new object to a mutable variable is local to the function in the python. Examples provided by @blair-conrad are great to understand this.

Alok Garg's user avatar

  • 2 Old but I feel obliged to correct it. Strings are passed by reference in both Java and C#, NOT by value –  John Commented Sep 11, 2019 at 16:39
  • 1 No. Everything is passed by value in c#. It is that the value of variable that is an object in c# is exactly and heap ID/address of the object. So when you set something in a function to a new object you set the variable in function to address. Passing by reference means passing an adres to value which is an address to the value for struct types but address to pointer in case of objects. –  jjaskulowski Commented Nov 10, 2021 at 21:13

I found other answers a little bit confusing and I had to struggle a while to grasp the concepts. So, I am trying to put the answer in my language. It may help you if other answers are confusing to you too. So, the answer is like this-

When you create a list-

you are actually creating an object of the class list:

Here, my_list is just a name given to the memory address (e.g., 140707924412080) of the object created by the constructor of the 'list' class.

When you pass this list to a method defined as

another reference to the same memory address 140707924412080 is created. So, when you make any changes/mutate to the object by using append method, it is also reflected outside the my_method1. Because, both the outer list my_list and local_list are referencing the same memory address.

On the other hand, when you pass the same list to the following method,

the first half of the process remains the same. i.e., a new reference/name local_list2 is created which points to the same memory address 140707924412080. But when you create a new list [1,2,3,4], the constructor of the 'list' class is called again and a new object is created. This new object has a completely different memory address, e.g., 140707924412112. When you assign local_list2 to [1,2,3,4], now the local_list2 name refers to a new memory address which is 140707924412112. Since in this entire process you have not made any changes to the object placed at memory address 140707924412080, it remains unaffected.

In other words, it is in the spirit that 'other languages have variables, Python have names'. That means in other languages, variables are referenced to a fixed address in memory. That means, in C++, if you reassign a variable by

the memory address where the value '1' was stored is now holding the value '2' And hence, the value '1' is completely lost. Whereas in Python, since everything is an object, earlier 'a' referred to the memory address that stores the object of class 'int' which in turn stores the value '1'. But, after reassignment, it refers to a completely different memory address that stores the newly created object of class 'int' holding the value '2'.

Hope it helps.

Bhanuday Sharma's user avatar

I am new to Python, started yesterday (though I have been programming for 45 years).

I came here because I was writing a function where I wanted to have two so-called out-parameters. If it would have been only one out-parameter, I wouldn't get hung up right now on checking how reference/value works in Python. I would just have used the return value of the function instead. But since I needed two such out-parameters I felt I needed to sort it out.

In this post I am going to show how I solved my situation. Perhaps others coming here can find it valuable, even though it is not exactly an answer to the topic question. Experienced Python programmers of course already know about the solution I used, but it was new to me.

From the answers here I could quickly see that Python works a bit like JavaScript in this regard, and that you need to use workarounds if you want the reference functionality.

But then I found something neat in Python that I don't think I have seen in other languages before, namely that you can return more than one value from a function, in a simple comma-separated way, like this:

and that you can handle that on the calling side similarly, like this

That was good enough for me and I was satisfied. There isn't any need to use some workaround.

In other languages you can of course also return many values, but then usually in the from of an object, and you need to adjust the calling side accordingly.

The Python way of doing it was nice and simple.

If you want to mimic by reference even more, you could do as follows:

which gives this result

Magnus's user avatar

  • 4 "But then I found something neat in Python that I don't think I have seen in other languages before, namely that you can return more than one value from a function" No, you can't. What you are doing is returning a single value, a tuple , which is what the expression a, b, c creates. You then use iterable unpacking to unpack that tuple into separate variables. Of course, in effect, you can think of this as "returning multiple values", but you aren't actually doing that, you are returning a container. –  juanpa.arrivillaga Commented Aug 12, 2020 at 19:45
  • 2 @juanpa.arrivillaga, yes, I was aware of that when I wrote my answer, I had just read about it. But I just described the whole thing in a practical way without going into the details of how it works and add unnecessary length to my answer. You can indeed return multiple values from a function, if it is done in an object or similar, like in a tuple (which in Python is taken care of in the neat way I showed). When I order things from a company, they can send me multiple things, even if it is all in one package. –  Magnus Commented Aug 13, 2020 at 9:01
  • This rambles a lot and is mostly off the topic of OP's question. It refers instead to this concept: stackoverflow.com/questions/354883 - which is well addressed by other existing Q&A. –  Karl Knechtel Commented Jul 12, 2023 at 17:22

Alternatively, you could use ctypes which would look something like this:

As a is a c int and not a Python integer and apparently passed by reference. However, you have to be careful as strange things could happen, and it is therefore not advised.

Julian wandhoven's user avatar

Use dataclasses . Also, it allows you to apply type restrictions (aka "type hints").

I agree with folks that in most cases you'd better consider not to use it.

And yet, when we're talking about contexts , it's worth to know that way.

You can design an explicit context class though. When prototyping, I prefer dataclasses, just because it's easy to serialize them back and forth.

Stepan Dyatkovskiy's user avatar

  • 1.9 mill views and 13 years later a decent solution comes up. I have implemented it calling the Holder "State" and adding a boolean value that can now be modified in a different function ... excellent and clean! –  Wolfgang Fahl Commented Nov 27, 2022 at 17:12
  • @WolfgangFahl several prior answers do functionally the same thing, just with a list element, ordinary object attribute etc. instead of a dataclass instance attribute. They all fundamentally work in the same way: since passing an object with reference semantics by value allows for mutation but not reassignment, we convert the desired reassignment into mutation by creating a wrapper object. –  Karl Knechtel Commented Jul 12, 2023 at 17:11
  • Agreed with @Karl Knechtel totally. Only reason I highlighted this case is that dataclasses support are quite friendly for serialization and provide minimum confusing API. So if somebody will extend your code there will be no temptation to perform list operations on what you supposed to use as a ref holder. –  Stepan Dyatkovskiy Commented Jul 16, 2023 at 8:35

There are already many great answers (or let's say opinions) about this and I've read them, but I want to mention a missing one. The one from Python's documentation in the FAQ section. I don't know the date of publishing this page, but this should be our true reference:

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se.

If you have:

and you call it like fn(a) , you're doing exactly what you do in assignment. So this happens:

An additional reference to SOMETHING is created. Variables are just symbols/names/references. They don't "hold" anything.

S.B's user avatar

Not the answer you're looking for? Browse other questions tagged python reference parameter-passing pass-by-reference or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Drill perpendicular hole through thick lumber using handheld drill
  • Trying to match building(s) to lot(s) when data has margin of error in QGIS
  • What came of the Trump campaign's complaint to the FEC that Harris 'stole' (or at least illegally received) Biden's funding?
  • What would be an appropriate translation of Solitude?
  • Browse a web page through SSH? (Need to access router web interface remotely, but only have SSH access to a different device on LAN)
  • Rocky Mountains Elevation Cutout
  • Non-existence of power divided structure on a maximal ideal of truncated polynomial rings (example from Koblitz)
  • In this page of Ein Yaakov on Sotah, near the bottom of the page, appears the word "Piska" in bold lettering. What does it signify?
  • Fast leap year check
  • Subject verb agreement - I as well as he is/am the culprit
  • Why is steaming food faster than boiling it?
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • Emacs calc: Apply function to vector
  • How to expand argument in the Expl3 command \str_if_eq?
  • Removing extra characters from code environment in beamer
  • Will "universal" SMPS work at any voltage in the range, even DC?
  • VBA: Efficiently Organise Data with Missing Values to Achieve Minimum Number of Tables
  • What does "break an arm" mean?
  • Why did early ASCII have ← and ↑ but not ↓ or →?
  • Is a thing just a class with only one member?
  • mmrm R package : No optimizer led to a successful model fit
  • The meaning of an implication in an existential quantifier
  • Should I write an email to a Latino teacher working in the US in English or Spanish?
  • Why Pythagorean theorem is all about 2?

different types of variable assignment in python

COMMENTS

  1. Variables in Python

    To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=): Python. >>> n = 300. This is read or interpreted as " n is assigned the value 300.". Once this is done, n can be used in a statement or expression, and its value will be substituted: Python.

  2. Different Forms of Assignment Statements 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

  3. Python Variables: A Beginner's Guide to Declaring, Assigning, and

    Just assign a value to a variable using the = operator e.g. variable_name = value. That's it. The following creates a variable with the integer value. Example: Declare a Variable in Python. num = 10. Try it. In the above example, we declared a variable named num and assigned an integer value 10 to it.

  4. Variables and Assignment

    The assignment operator, denoted by the "=" symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name "x". After executing this line, this number will be stored into this variable. Until the value is changed or the variable ...

  5. Python's Assignment Operator: Write Robust Assignments

    Python's assignment operators allow you to define assignment statements. This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

  6. Python Variables

    This means that the type of a variable is interpreted at runtime and you can assign different types of values to the same variable. Example: var = 10 # var is an integer var = "Hello" # Now var is a string var = [1, 2, 3] # Now var is a list How to Use Type Annotations for Variables in Python? Type annotations in Python provide a way to specify ...

  7. Python Variables

    Python variables are used to store and manipulate data in code. Variable assignment allows developers to assign a name to a value and reference it later. Proper variable naming conventions are essential for effective programming. Python supports different variable types, including integers, floats, strings, and lists.

  8. Variables & Assignment

    In general, assigning a variable b to a variable a will cause the variables to reference the same object in the system's memory, and assigning c to a or b will simply have a third variable reference this same object. Then any change (a.k.a mutation) of the object will be reflected in all of the variables that reference it (a, b, and c).

  9. Python Variables

    Python variables can hold various data types, including integers, floats, strings, booleans, tuples and lists: Integers are whole numbers, both positive and negative. Floats are real numbers or numbers with a decimal point. Strings are sequences of characters, namely words or sentences.

  10. Python Variable Assignment. Explaining One Of The Most Fundamental

    Declare And Assign Value To Variable. Assignment sets a value to a variable. To assign variable a value, use the equals sign (=) myFirstVariable = 1 mySecondVariable = 2 myFirstVariable = "Hello You" Assigning a value is known as binding in Python. In the example above, we have assigned the value of 2 to mySecondVariable.

  11. Variable Assignment (Video)

    Variable Assignment. Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=).

  12. Variables, Assignment, Types and Arithmetic

    Variables in python. The purpose of a variable is to store information within a program while it is running. A variable is a named storage location in computer memory. Use the name to access the value. To store a value in a variable, use the = operator (called the assignment operator). An = sign in Python is nothing like an equal sign in ...

  13. Different Forms of Assignment Statements in Python

    The value assigned to the variable can be of any data type supported by python programming language such as integer, string, float Boolean, list, tuple, dictionary, set etc. Types of assignment statements. The different types of assignment statements are as follows. Basic assignment statement. Multiple assignment statement. Augmented assignment ...

  14. Variable in Python

    Let's define what a variable is in Python. It is a named location in the computer's memory that stores a value. It is like a container that can hold different types of data, such as numbers, strings or booleans. To create a variable in Python, you need to give it a name and assign a value to it using the assignment operator =.

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

  16. Python Operators (With Examples)

    Assignment operators are used to assign values to variables. For example, # assign 5 to x x = 5. Here, = is an assignment operator that assigns 5 to x. Here's a list of different assignment operators available in Python.

  17. Python Variables and Literals (With Examples)

    They can be numbers, characters, or strings, etc. For example, 'Hello, World!', 12, 23.0, 'C', etc. Literals are often used to assign values to variables or constants. For example, site_name = 'programiz.com'. In the above expression, site_name is a variable, and 'programiz.com' is a literal. There are different types of literals in Python.

  18. Python Variables

    Create Number, String, List variables. We can create different types of variables as per our requirements. Let's see each one by one. Number. A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric ...

  19. Different Types of Variables in Python with Examples

    Here are some common types of variables: 1. Python Numbers. In Python, the Numbers variable type or data type holds values that number. You make a number object when you give it a value. For example: var1 =1. var2 =10. You can also use the del statement to remove the reference to a number object.

  20. python

    2. Python is dynamically typed language which means that the type of variables are decided in running time. As a result python interpreter will distinguish the variable's types (in running time) and give the exact space in memory needed. Despite being dynamically typed, Python is strongly typed, forbidding operations that are not well-defined ...

  21. How to declare variable type, C style in Python

    Edit: Python 3.5 introduced type hints which introduced a way to specify the type of a variable. This answer was written before this feature became available. There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist. This will bind the three names to the same object: x = y = z = 0

  22. What happens when you assign the value of one variable to another

    A Python variable's name is a key in the global (or local) namespace, which is effectively a dictionary. The underlying value is some object in memory. Assignment gives a name to that object. Assignment of one variable to another variable means both variables are names for the same object.

  23. Booleans :: Introduction to Python

    Resources Slides In Python, Boolean values are stored in the bool data type. Variables of the bool data type can only store one of two values, True or False. So, a Boolean value is really the simplest data value we can imagine - it is a single binary bit representing a value of True or False. To create a Boolean variable in Python, we can simply assign those values to a variable in an ...

  24. python

    Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. ... a variable is a memory space that is able to capture the value of the type. In Python, a variable is a name (captured internally as a string) bound to the reference variable that holds the ...