Understanding Variables in Python 3

By Lenin Mishra

What is a Variable in Python?

A Python variable is a reserved memory location that stores values.

Python is a dynamically typed language. Unlike statically typed languages like C and C++, the data type of a variable in Python is defined at runtime.

Also, in Python, the variable type can change during the code lifetime. This is different for statically typed languages, where you have to declare a variable with a specific data type, and values assigned to it during its lifetime must always have the same type.

Code

# Store a string
x = "Pylenin"
print(x)

# Store an integer
x = 10
print(x)

# Store a float
x = 3.5
print(x)

# Store a list
x = [1, 2, 3]
print(x)

You can run the above code and the output will look like the below.

Output

Pylenin
10
3.5
[1, 2, 3]

Basically, you can change the content and data type of variable during the course of a program.

Chained Assignment of Variables

In Python, you can also perform chained assignments, which makes it possible to assign the same value to multiple variables simultaneously:

Code

x = y = z = 100
print(x, y, z)

Output

100, 100, 100

Variable Assignment - What happens behind the scenes?

x = "Pylenin"

When you make the above assignment, Python creates a string object and assigns the variable x to point to the string object.

Code

x = "Pylenin"
print(type(x))

Output

<class 'str'>

Now what happens, if you run the following code?

Code

x = "Pylenin"
print(type(x))

y = x

Now there is another variable y in our code and that is set equal to x. When you run the code, Python won’t create a new variable. It will create a symbolic reference y that points to the same string object.

You can confirm this by finding the id of both the variables. Whenever an object is created in Python, it is assigned an unique identity. You can find the id of variables, by using the id() built-in function. Code

x = "Pylenin"
print(type(x))

y = x
print(id(y), id(x))

Output

<class 'str'>
1957481302640 1957481302640

As you can see, both x and y have the same id.