Assigning a variable in Python is as easy as typing x = 5 into the console. There you go! Now you’ve got a variable named x that holds the value 5. But there’s quite a bit more to know about variables in Python.
Learn what a Python variable is, what data types there are in Python, how variable scope works in Python, and how to choose a variable name in Python.
What Is a Python Variable?
Unlike in the C programming language, in Python a variable is not bound to a certain object. Rather, variables in Python work as pointers to objects. This means they’re not restricted to a specific type and can be assigned dynamically. For instance, you can assign a value of one data type to a variable, and to another data type directly afterward:
This would throw an error in a statically typed language like C or Java. In those languages, a variable’s type has to be specified before it may be assigned to a value. This process is called variable declaration. But in Python, we don’t declare variables, we simply assign them. In short, we can think of a variable in Python as a name for an object.
In the example above, after we reassigned x to a new object, the old object is no longer referenced by any variable and is up for deletion. In other words, it’s been overwritten.
What Data Types are There in Python?
Mutable vs. Immutable Data Types
So what type of object could a Python variable refer to? We’ll first need to distinguish between mutable and immutable data types. An immutable object cannot be changed once created. However, mutable data types may be shortened, lengthened, or otherwise modified. An example of a mutable object in Python is the list.
We’ve created a new list object that holds three elements. We assigned it the name (or variable) sample_list. We’ll now use the id() function to check at which memory address it’s stored.
What if we were to modify our list by adding an element? We could do this in two ways, both of which are shown below:
We’ve expanded our list by one letter. Let’s check the variable’s ID again.
As expected, the object’s address has remained the same. In contrast, once we modify an immutable data type, we effectively create a new object that’s referenced by the same variable as the original object. In the next example, we’ll create a string object called adam. In Python, you can use both double and single quotes to create strings.
By adding the letter ‘a’ to our string, we created a new object stored under a different address but referenced by the same variable as the original ‘adam’ string.
We’ll look at one more example to illustrate how Python’s variables function as pointers. After assigning an existing list object to a new variable, how would we expect the two variables’ addresses to look like?
The IDs for both liste and lista are the same, because the two variables are just different names for the same object.
How to Define Variables for Other Data Types in Python
As explained above, Python doesn’t require the explicit declaration of a variable’s type, making it a dynamically typed language. This is also referred to as duck typing, after the adage that if something “walks like a duck and quacks like a duck, then it must be a duck.”
Let’s look at how to duck type different objects in Python. We’ve already talked about creating list and string objects. How about other object types, say an integer? In that case, you would simply write a number with no floating point.
To create a floating point number, just add a period:
A set (a collection of unique elements) is created using curly brackets:
Now, to define a tuple (like a list, but immutable), use round brackets followed by a comma:
For a dictionary, use curly brackets again, but separate the key and value using a colon:
How Does Variable Scope Work in Python?
Scope is an important concept in programming. It describes the space within which a variable references an object. We mainly distinguish between local and global scope. A global variable is defined outside of a function, but we can use it within that function.
A local variable, however, is created within a function and cannot be used outside of it. If the local and global variables share the same name, the former would overwrite the latter for the duration of the function’s run time:
For the duration of the runtime of the paradise() function, x references ‘Eve.’ However, if we were to call the name variable again outside of the function, it would again be the global variable containing the ‘Adam’ string.
We can convert a locally defined variable into a global one by using the global keyword:
After running the paradise() function, the variable name now holds the name ‘Eve.’
How to Choose a Variable Name in Python
As any programming language, Python has certain variable naming conventions. While some of those are rules that produce syntax errors if broken, others are simply considered to be good, Pythonic style.
- A variable can consist of upper- and lowercase letters, the digits 0-9 and the underscore character.
- The first character of a variable cannot be a digit.
- Keywords like if or the Boolean True are reserved and cannot be used as variable names.
- Variables are case-sensitive; therefore x is different from X.
Conventions as Defined in PEP 8
- Use snake_case for variable names (instead of CamelCase)
- Don’t use names that look like the digits 1 and 0 (such as lowercase L)
In addition, it’s good practice to use descriptive variables rather than obscure ones. Granted, variables like x and y look cool and make your code shorter, but it’s usually better to choose longer variable names that actually describe the object they refer to. However, it’s ultimately up to you to implement these recommendations.
Fun Fact About Variable Assignment in Python
When it comes to variable assignment, Python has some syntactic sugar to offer. This is what programmers call features that don’t change a language’s expressiveness but do make life easier for the person writing the code.
If you’d like to assign values to multiple variables, you can do that in one line. Simply put all the variables that you want to assign into one tuple — rather than writing one line for each assignment. This is called multiple assignment, or tuple unpacking.
This property is quite useful when calling a function that returns multiple values. Just assign them in one line:
Now that you’ve learned quite a bit about defining variables in Python, it’s time to take the next step! Check out our Intro to Programming Nanodegree, a program that could very well be your first step towards careers in Web and App Development, Machine Learning, Data Science, AI, and more.