- Coding Fundamentals and Patterns
Show previous content
Values can be reassigned to variables in Python. When variables are reassigned, their value changes to that of the newer value specified, and the previous value is lost.
Let's look at an example. We can reassign variable values in Python as follows.
The reassignment works similarly to how we create the variable. We only provide a different value than what was stored before. Here, the initial value of a was 10 , which was reassigned to 20 from the second line in the above code block.
Show following content
- Basic Arrays Interview Questions
- Binary Search Trees Interview Questions
- Dynamic Programming Interview Questions
- Easy Strings Interview Questions
- Frontend Interview Questions
- Graphs Interview Questions
- Hard Arrays Interview Questions
- Hard Strings Interview Questions
- Hash Maps Interview Questions
- Linked Lists Interview Questions
- Medium Arrays Interview Questions
- Queues Interview Questions
- Recursion Interview Questions
- Sorting Interview Questions
- Stacks Interview Questions
- Systems Design Interview Questions
- Trees Interview Questions
- All Courses, Lessons, and Challenges
- Data Structures Cheat Sheet
- Free Coding Videos
- Bit Manipulation Interview Questions
- Python Interview Questions
- Java Interview Questions
- SQL Interview Questions
- QA and Testing Interview Questions
- Data Engineering Interview Questions
- Data Science Interview Questions
- Blockchain Interview Questions
- Lesson 6: Game Server - Performance Optimization
- 0/1 Knapsack Problem
- Implementing CRDTs
- Closing Thoughts on CRDTs
- Crash Course Update: Day 41
Buy 2+, save 55% on books & eBooks through December 1. Use code BOOKSGIVING. Learn more.
Home > Articles > Open Source > Python
Understanding Python Basics for Raspberry Pi
- Nov 21, 2013
- Producing Python Script Output
- Formatting Scripts for Readability
- Understanding Python Variables
Assigning Value to Python Variables
- Learning About Python Data Types
- Allowing Python Script Input
This chapter is from the book
This chapter is from the book
Assigning a value to a Python variable is fairly straightforward. You put the variable name first, then an equal sign (=), and finish up with the value you are assigning to the variable. This is the syntax:
Listing 4.13 creates the variable coffee_cup and assigns a value to it.
LISTING 4.13 Assigning a Value to a Python Variable
As you see in Listing 4.13, the print function can output the value of the variable without any quotation marks around it. You can take output a step further by putting a string and a variable together as two print function arguments. The print function knows they are two separate arguments because they are separated by a comma ( , ), as shown in Listing 4.14.
LISTING 4.14 Displaying Text and a Variable
Formatting variable and string output.
Using variables adds additional formatting issues. For example, the print function automatically inserts a space whenever it encounters a comma in a statement. This is why you do not need to add a space at the end of My coffee cup is full of , as shown in Listing 4.14. There may be times, however, when you want something else besides a space to separate a string of characters from a variable in the output. In such a case, you can use a separator in your statement. Listing 4.15 uses the sep separator to place an asterisk ( * ) in the output instead of a space.
LISTING 4.15 Using Separators in Output
Notice you can also put variables in between various strings in your print statements. In Listing 4.15, four arguments are given to the print function:
- The string "I love my"
- The variable coffee_cup
- The string "!"
- The separator designation '*'
The variable coffee_cup is between two strings. Thus, you get two asterisks ( * ), one between each argument to the print function. Mixing strings and variables in the print function gives you a lot of flexibility in your script’s output.
Avoiding Unassigned Variables
You cannot use a variable until you have assigned a value to it. A variable is created when it is assigned a value and not before. Listing 4.16 shows an example of this.
LISTING 4.16 Behavior of an Unassigned Variable
Assigning long string values to variables.
If you need to assign a long string value to a variable, you can break it up onto multiple lines by using a couple methods. Earlier in the hour, in the “Formatting Scripts for Readability” section, you looked at using the print function with multiple lines of outputted text. The concept here is very similar.
The first method involves using string concatenation ( + ) to put the strings together and an escape character ( \ ) to keep a linefeed from being inserted. You can see in Listing 4.17 that two long lines of text were concatenated together in the assignment of the variable long_string .
LISTING 4.17 Concatenating Text in Variable Assignment
Another method is to use parentheses to enclose your variable’s value. Listing 4.18 eliminates the +\ and uses parentheses on either side of the entire long string in order to make it into one long string of characters.
LISTING 4.18 Combining Text in Variable Assignment
The method used in Listing 4.18 is a much cleaner method. It also helps improve the readability of the script.
By the Way: Assigning Short Strings to Variables
You can use parentheses for assigning short strings to variables, too! This is especially useful if it helps you improve the readability of your Python script.
More Variable Assignments
The value of a variable does not have to only be a string of characters; it can also be a number. In Listing 4.19, the number of cups consumed of a particular beverage are assigned to the variable cups_consumed .
LISTING 4.19 Assigning a Numeric Value to a Variable
You can also assign the result of an expression to a variable. The equation 3+1 is completed in Listing 4.20, and then the value 4 is assigned to the variable cups_consumed .
LISTING 4.20 Assigning an Expression Result to a Variable
You will learn more about performing mathematical operations in Python scripts in Hour 5, “Using Arithmetic in Your Programs.”
Reassigning Values to a Variable
After you assign a value to a variable, the variable is not stuck with that value. It can be reassigned. Variables are called variables because their values can be varied. (Say that three times fast.)
In Listing 4.21, the variable coffee_cup has its value changed from coffee to tea . To reassign a value, you simply enter the assignment syntax with a new value at the end of it.
LISTING 4.21 Reassigning a Variable
Did You Know: Variable Name Case
Python script writers tend to use all lowercase letters in the names of variable whose values might change, such as coffee_cup . For variable names that are never reassigned values, all uppercase letters are used (for example, PI = 3.14159 ). The unchanging variables are called symbolic constants .
- 🔖 Save To Your Account
InformIT Promotional Mailings & Special Offers
I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.
Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.
This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.
Collection and Use of Information
To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:
Questions and Inquiries
For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.
For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.
Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.
Contests and Drawings
Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.
If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply www.informit.com/u.aspx , enter your email address in the field supplied, and click the Submit button. On the resulting page, check the box of the particular item(s) you would no longer like to receive, and click the Unsubscribe button-->email [email protected] .
On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.
We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form .
Other Collection and Use of Information
Application and system logs.
Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.
Cookies and Related Technologies
Do Not Track
This site currently does not respond to Do Not Track signals.
Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.
This site is not directed to children under the age of 13.
Pearson may send or direct marketing communications to users, provided that
- Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
- Such marketing is consistent with applicable law and Pearson's legal obligations.
- Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
- Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.
Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.
Correcting/Updating Personal Information
If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page . If a user no longer desires our service and desires to delete his or her account, please contact us at [email protected] and we will process the deletion of a user's account.
Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx .
Sale of Personal Information
Pearson does not rent or sell personal information in exchange for any payment of money.
While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to [email protected] .
Supplemental Privacy Statement for California Residents
California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.
Sharing and Disclosure
Pearson may disclose personal information, as follows:
- As required by law.
- With the consent of the individual (or their parent, if the individual is a minor)
- In response to a subpoena, court order or legal process, to the extent permitted or required by law
- To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
- In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
- To investigate or address actual or suspected fraud or other illegal activities
- To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
- To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.
This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.
Requests and Contact
Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.
Changes to this Privacy Notice
We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.
Last Update: November 17, 2020
- View Your Cart
- 👤 Sign In
- Business & Management
- Cloud Computing & Virtualization
- Digital Photography
- Graphics & Web Design
- Home & Office Computing
- Information Technology
- Mobile Application Development & Programming
- Open Source
- Operating Systems, Server
- Software Development & Management
- Web Development
- Web Services
- Practice Tests
- Web Editions
- Deals & Promotions
- Video Training
- Addison-Wesley Professional
- Adobe Press
- Cisco Press
- Microsoft Press Store
- Oracle Press Books
- Pearson IT Certification
- Que Publishing
- Sams Publishing
- Affiliate Program
- Chapters & Articles
- Popular Topics
- Product Registration
- Special Offers & Newsletter
- Press and Media Relations
- Product Review Team
- User Groups
- Legal Notice
- Ordering Information
- Privacy Notice
- Do Not Sell My Personal Information
- Write for Us
Can variables be reassigned to another data type?
After a variable is assigned to an initial value, can the variable later be reassigned to another value that is of a different data type than its initial value?
Yes, variables in Python can be reassigned to a new value that is a different data type from its current value. In fact, variables can be reassigned to any valid value in Python, regardless of its current value.
Variables are essentially like an empty box, that can contain something like a string, number, or other value. When you assign it a value, the box will contain that value, and when you reassign it, it will empty out the old value, and the new value will be placed inside of it.
Do we place a divider or How do we know that the value of the second variable will be taken?
The assignment operator, = (it is not an “equals sign”), does the work. Each time the Python interpreter sees this symbol, three things happen:
- the expression on the right side of the symbol is evaluated to obtain a value.
- that value is placed in a memory location
- the address of that location is assigned to the variable on the left of the symbol.
Once this is accomplished, the value is bound to the variable.
so can we define a variable a specific type? like var should be an integer type throughout the program. var = 10 And if any other type value is assigned to var it should throw an error stating type mismatch? var = ‘sleep’.
Not in Python! Python types variables at the time of assignment. Some people call it “duck typing,” as in, “if it walks like a duck…” etc.
You can reassign any variable at any time without error.
Declaration and definition are done at the same time?
Not explicitly. In Python, we do not declare variables. The assignment statement does everything: it tells the interpreter to evaluate the expression on the right, place its value in memory, and assign the memory address to the variable on the left.
The interpreter keeps track of the number of references to the address, and when that number is zero, the memory is released (actually, tagged for “garbage collection”). Any type of object can go in any address. Again, there is no explicit typing or variable declaration; it’s all “under the hood.”
- What is the life span of a variable in python?
- Is there any concept of variable that is not recently used is GC’d or something like that?
hi Patrickd , thank you for your answers
Yes, Python uses garbage collection. The life span is as long as it is referenced and then once it isn’t anymore however long it takes before the garbage collection gets it - as a side note, it is possible to run the GC manually.
One interesting life span is for default values of functions, they are evaluated once and not each time the function is called, so if you used something mutable you could have some weird side effects, like so:
Can you please clarify the concept of duck typing & duck test?
Jephos249 this was really helpful. Thank you.
A post was split to a new topic: What is that supposed to mean?
How can we ensure that we don’t accidentally perform operations on a variable after reassigning it to another data type? Are there any best practices for handling reassignment of variables in Python?
my question is - for example in the lesson there is meal = “english muffin” but later on it used again and provides next data with different wards so do you have to keep repeating it in that case if u gotta use it multiple times or u can say meal1 and for next one meal2 and meal 3? or it doesn’t matter because it knows the pattern/can tell what goes first what second? Is it better to lable them diffentet like “meal1” and so on , right?
Basic understanding would say that is only necessary when you want to keep the original value as well as a new one. So for instance, lets say you wanted to use multiple variables within a single sentence. You would then define each variable with a new command. Here is an article that will better explain it: Why change a variable rather than just create a new one? - Get Help / Python - Codecademy Forums
@swapnilb007 it’s colloquial, it means that Python looks at the value and determines the type of the variable based on what it notices as attributes - like the saying ‘If it walks like a duck and it quacks like a duck, then it must be a duck’.
I.e.: If the variable is ‘XXX’. Python looks at it and goes, well it has quotes around it, by all conventions it should be a string. Another example, if the variable is 42. Python looks at it and determines that without any other information based on the fact it’s numeric in absence of anything else it is probably numeric.
There’s a wikipedia artiicle that explicitly explains this in the context of Python 3:
P.S: Duck test is also in there in the wikipedia article.
@ajax3916882621 Python doesn’t declare variable types nor track variable types as other have said. The onus is really on you the programmer to make sure you keep track of the variables you created and how you use them. If you are reassigning variables often, it would be good to have a great name for it so that it’s not confusing when you reassign them in a program.
It’s not the biggest deal in the world. The worst that happens is that you run into an error and you go back and fix the variable.
How to assign a variable in Python
Sign in to change your settings
Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here .
How can you assign a variable in Python?
An equals sign assigns in Python
In Python, the equal sign ( = ) assigns a variable to a value :
This is called an assignment statement . We've pointed the variable count to the value 4 .
We don't have declarations or initializations
Some programming languages have an idea of declaring variables .
Declaring a variable says a variable exists with this name, but it doesn't have a value yet . After you've declared the variable, you then have to initialize it with a value.
Python doesn't have the concept of declaring a variable or initializing variables . Other programming languages sometimes do, but we don't.
In Python, a variable either exists or it doesn't:
If it doesn't exist, assigning to that variable will make it exist:
Valid variable names in Python
Variables in Python can be made up of letters, numbers, and underscores:
The first character in a variable cannot be a number :
And a small handful of names are reserved , so they can't be used as variable names:
Reassigning a variable in Python
What if you want to change the value of a variable ?
The equal sign is used to assign a variable to a value, but it's also used to reassign a variable:
In Python, there's no distinction between assignment and reassignment .
Whenever you assign a variable in Python, if a variable with that name doesn't exist yet, Python makes a new variable with that name . But if a variable does exist with that name, Python points that variable to the value that we're assigning it to .
Variables don't have types in Python
Note that in Python, variables don't care about the type of an object .
Our amount variable currently points to an integer:
But there's nothing stopping us from pointing it to a string instead:
Variables in Python don't have types associated with them. Objects have types but variables don't . You can point a variable to any object that you'd like.
Type annotations are really type hints
You might have seen a variable that seems to have a type. This is called a type annotation (a.k.a. a "type hint"):
But when you run code like this, Python pretty much ignores these type hints. These are useful as documentation , and they can be introspected at runtime. But type annotations are not enforced by Python . Meaning, if we were to assign this variable to a different type, Python won't care:
What's the point of that?
Well, there's a number of code analysis tools that will check type annotations and show errors if our annotations don't match.
One of these tools is called MyPy .
Type annotations are something that you can opt into in Python, but Python won't do type-checking for you . If you want to enforce type annotations in your code, you'll need to specifically run a type-checker (like MyPy) before your code runs.
Use = to assign a variable in Python
Assignment in Python is pretty simple on its face, but there's a bit of complexity below the surface.
For example, Python's variables are not buckets that contain objects : Python's variables are pointers . Also you can assign into data structures in Python.
Also, it's actually possible to assign without using an equal sign in Python. But the equal sign ( = ) is the quick and easy way to assign a variable in Python.
What comes after Intro to Python?
Intro to Python courses often skip over some fundamental Python concepts .
Sign up below and I'll explain concepts that new Python programmers often overlook .
Series: Assignment and Mutation
Python's variables aren't buckets that contain things; they're pointers that reference objects.
The way Python's variables work can often confuse folks new to Python, both new programmers and folks moving from other languages like C++ or Java.
To track your progress on this Python Morsels topic trail, sign in or sign up .
Sign up below and I'll share ideas new Pythonistas often overlook .
Python's variables are not buckets that contain objects; they're pointers. Assignment statements don't copy: they point a variable to a value (and multiple variables can "point" to the same value).
- Table of Contents
- Course Home
- Peer Instruction (Instructor)
- Peer Instruction (Student)
- Change Course
- Instructor's Page
- Progress Page
- Edit Profile
- Change Password
- Scratch ActiveCode
- Scratch Activecode
- Instructors Guide
- About Runestone
- Report A Problem
- 2.1 Variables, Expressions and Statements
- 2.2 Values and Data Types
- 2.3 Type conversion functions
- 2.4 Variables
- 2.5 Variable Names and Keywords
- 2.6 Statements and Expressions
- 2.7 Operators and Operands
- 2.9 Order of Operations
- 2.10 Reassignment
- 2.11 Updating Variables
- 2.12 Glossary
- 2.13 Exercises
- 2.9. Order of Operations" data-toggle="tooltip">
- 2.11. Updating Variables' data-toggle="tooltip" >
2.10. Reassignment ¶
As we have mentioned previously, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).
The first time bruce is printed, its value is 5, and the second time, its value is 7. The assignment statement changes the value (the object) that bruce refers to.
Here is what reassignment looks like in a reference diagram:
It is important to note that in mathematics, a statement of equality is always true. If a is equal to b now, then a will always equal to b . In Python, an assignment statement can make two variables refer to the same object and therefore have the same value. They appear to be equal. However, because of the possibility of reassignment, they don’t have to stay that way:
Line 4 changes the value of a but does not change the value of b , so they are no longer equal. We will have much more to say about equality in a later chapter.
2.10.1. Developing your mental model of How Python Evaluates ¶
Its important to start to develop a good mental model of the steps Python takes when evaluating an assignment statement. In an assignment statement Python first evaluates the code on the right hand side of the assignment operator. It then gives a name to whatever that is. The (very short) visualization below shows what is happening.
In the first statement a = 5 the literal number 5 evaluates to 5, and is given the name a . In the second statement, the variable a evaluates to 5 and so 5 now ends up with a second name b .
In some programming languages, a different symbol is used for assignment, such as <- or := . The intent is that this will help to avoid confusion. Python chose to use the tokens = for assignment, and == for equality. This is a popular choice also found in languages like C, C++, Java, and C#.
Check your understanding
After the following statements, what are the values of x and y?
- x is 15 and y is 15
- Look at the last assignment statement which gives x a different value.
- x is 22 and y is 22
- No, x and y are two separate variables. Just because x changes in the last assignment statement, it does not change the value that was copied into y in the second statement.
- x is 15 and y is 22
- Look at the last assignment statement, which reassigns x, and not y.
- x is 22 and y is 15
- Yes, x has the value 22 and y the value 15.
Everything You Need to Know About Python Variables
Updated: January 20, 2023
Published: November 03, 2022
Python is one of the most sought-after programming languages nowadays because it allows developers to focus on implementation rather than spend time writing complex programs. The ease of access and readability makes Python ideal for beginners who want to learn the basics of coding. To advance as a Python programmer, you need to understand the basics of variables.
In this article, we will explore what variables are in Python and how to create them. We will also discuss best practices and common mistakes people make when working with variables. By the end of this article, you should have a strong understanding of how variables work in Python. Let's get started.
What is a variable in Python?
Python variables are like containers that hold values. They can be used to store anything from simple data types like integers and strings to more complex data structures like lists and dictionaries. You can think of them as labels you attach to values to keep track of them.
Variables are useful because they can help you keep track of different pieces of information in your program. For example, if you were writing a program to keep track of your expenses, you might want to use variables to store the amount of money you spent on each purchase. This would be much easier than remembering all the different values yourself.
Next, we will look at different ways to form a variable. Let's begin with discussing how to name a Python variable.
Name a Variable in Python
When naming variables in Python, there are a few rules that you need to follow:
- Variable names can only contain letters, numbers, and underscores.
- Variable names cannot start with a number.
- Variable names are case sensitive (my_variable is different from My_Variable).
There are also a few conventions that people follow when naming variables:
- Variable names should be short but descriptive.
- Variable names should be all lowercase.
- If you need to use multiple words in your variable name, you can separate them with underscores. Example: my_very_long_variable_name = 42.
Remember to be as clear and concise as possible when naming variables. This will help make your code easier to read and understand.
Some examples of good variable names:
Some examples of names you should avoid:
Create a Variable in Python
Creating a variable in Python is simple. Just use the assignment operator (=) to assign a value to a variable.
Consider the following example:
In the code example, we will create a variable called my_variable and assign the value 42 to it. You can then use this variable in your code by referencing its name:
The code above prints the value of my_variable to the screen.
Declare a Variable in Python
Unlike other programming languages; Python does not require you to declare variables explicitly before using them. This means you can create a variable and start using it without any declaration. Since Python is a dynamically-typed language, variables are created when you first assign a value to them.
Take a look at the following example:
This code will create the variable my_variable and automatically set its type to int (integer) .
Note: String variables can be declared using either single or double quotes.
Reassign a Variable in Python
You can reassign values of different types to the same variable without issue.
Now my_variable will be of type str (string) . This is one of the benefits of using a dynamically-typed language - you don't need to worry about declaring variables ahead of time; you can just start using them.
Assign Multiple Variables at Once
In Python, you can assign multiple variables at the same time. This is often useful when extracting multiple values from a data structure, like a list or dictionary .
Review the following example:
In this code we assign the value 0 to the variable a , and the value 42 to the variable b . You can also use this syntax to swap the values of two variables:
This will take the value of b and assign it to a , and vice versa.
You can also assign multiple variables from a list:
This will assign the first value in the list ( 0 ) to a , the second value ( 42 ) to b , and the third value ( "hello" ) to c .
Note: This only works if the number of variables being assigned matches the number of values in the list. Otherwise, you will get an error.
Get the Type of Variable in Python
It's often useful to know the variable type in Python. You can use the type() function to find out:
This would return int, str, list, dict, tuple, etc., depending on the type of the variable.
Take a look at the example below:
You can also use the isinstance() function to check if a variable is of a certain type:
This would return True or False depending on whether or not my_variable is a string.
Remove a Variable in Python
If you want to remove a variable in Python, you can use the del keyword.
This will remove the variable my_variable from your namespace. After running this code, trying to access my_variable will result in an error.
You can also remove multiple variables at once by using the del keyword with a list of variable names:
This will remove both my_variable and my_other_variable from your namespace.
Generally, you won't need to delete variables very often. However, there are a few situations where it can be useful:
- When you are finished with a large data structure and want to free up memory
- When you want to make sure a variable can't be accessed or modified anymore
- When you want to avoid potential name collisions with new variables
Keep in mind that once you delete a variable, it is gone for good. There is no way to recover it, so make sure you only delete variables that you no longer need.
Local and Global Variables in Python
When working with variables in Python, you need to be aware of the scope of the variable. The scope of a variable is the part of your code where the variable is available. When you create a variable in Python, it is either a local or global variable.
A local variable is only available within the scope in which it is created. For example, if you create a variable inside of a function, it will only be available inside of that function.
A global variable is available throughout your entire Python program. For example, if you create a variable at the top level of your program (outside of any functions), it will be globally available throughout your program.
Simply stated, if you wish to use the same variable throughout your program declare it as a global variable; whereas, if you want to utilize that variable in only one function or procedure of your code, declare it as a local variable.
Note: You should generally avoid using global variables in your code, as they can lead to unexpected results and make your code difficult to debug.
Below is an example of a global variable:
In this example, the variable my_var is declared as a global variable. This means that it can be accessed from anywhere in your program. In the function my_func() , we simply print the value of my_var to the screen.
Now, let's say we wanted to create a local variable inside of the function instead:
In this example, the variable my_var is declared as a local variable inside of the function. This means that it can only be accessed from within the function. If we try to access it outside of the function, we will get an error:
This would cause an error because the variable my_var is not available outside of the function.
Using the global keyword, you can also declare variables as global inside of a function.
In this code, we use the global keyword to declare the variable my_var as a global variable inside of the function. This means that we can access it from anywhere in our program, even outside of the function.
This wraps up the several different ways to form a variable. Next, we will discuss some common mistakes to keep in mind.
Common Pitfalls when Working with Variables in Python
There are a few things to watch out for when working with variables in Python. Let's take a look at some of the most common mistakes people make.
Mistake #1: Not Assigning a Value
One common mistake is trying to use a variable before it has been assigned a value.
This would cause an error because my_variable has not been assigned a value yet. You would need to do something like this first:
This will print None to the screen, which is the default value for variables that have not been initialized with a specific value.
Mistake #2: Reassigning a Constant Value
Another common mistake is trying to reassign a constant value. For example, you might see code like this:
The example above would cause an error because PI is a constant value (it is set to math.pi by default) and cannot be changed.
A constant value is a value that cannot be changed. In Python, there are a few built-in constants, such as None, True, and False. You can also create your own constants by using the constant module. The constant module is a module that allows you to create your own constants in Python by using the import keyword.
If you want to reassign the value of PI , you would need to do something like this:
This would reassign the value of PI to "Hello, world!" in the math module.
With that said, constants are not really used in Python that often, so you probably won't run into this issue very often.
Mistake #3: Using Undeclared Variables
Another common mistake is using an undeclared variable.
Let's look at an example:
This will cause an error because the variable x has not been declared yet. You would need to do something like this first:
This will declare the variable x and assign the value 42 to it, then print the value of x to the screen.
Hopefully this has cleared up some of the confusion around variables in Python.
Final Thoughts on Variables in Python
Variables are an essential part of programming in any language. Overall, Python variables are simple to create and use. Just remember to choose meaningful names, and don't delete any variables that you might need later. Also, be careful of the variable scope when working with functions.
Now that you know all about variables in Python, you're ready to tackle some other important concepts in Python programming!
Don't forget to share this post!
Introduction to the Python Replace String Method
How to Remove Duplicated Data in Pandas: A Step-by-Step Guide
How to Use Series in Pandas to Store Your Data
How to Use Python in Web Development [+ Examples]
Why Your Business is Incomplete Without a Python Chatbot: A Step-by-Step Guide to Building One
Unlock Hidden Insights in Your Data: 5 Python Machine Learning Strategies You Haven't Tried Yet
How to Find Pandas DataFrame Size, Shape, and Dimensions Properties
Python Zip: What It Is and How It Works
What Is Python? [+ How to Learn and Use It]
My Mom Built a Video Game With ChatGPT: Here's How
A guide for marketers, developers, and data analysts.
Something went wrong. Wait a moment and try again.
Dive into new course Game Development with Phaser 👾
💥 ALL NEW: Code Adventures! ⚡ Dare to embark on a front end coding adventure 🌟
New AI course: Introduction to Computer Vision 💻
Learn about our new Community Discord server here and join us on Discord here !
New workshop: Discover AI-powered VS Code extensions like GitHub Copilot and IntelliCode 🤖
New course! Join Dan as he uses generative AI to design a website for a bakery 🥖
Jump into our new React Basics course 😎
Get job-ready with our Career Toolbox Track's career advice, resume tips, and more 🧰
🤖 Check out all our AI content here 👀
Students: got a cool project or resource to share? Submit it to Treehouse Links ! 🤩
Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
- Watch Video
Python Regular Expressions in Python Introduction to Regular Expressions Reading Files
Hara Gopal K
Storing regex in a variable.
in the following code, i can't seem to store a re-expression in a variable. it's taking the literal value instead, any idea why ? In below example, the expression r'genre should take the value from a list named books.
I'd replace the line
This answer is so late and probably solved already.
But as I'm trying to browse every question in every video to learn more, I think that these posts and answers will be very helpful for future course students.
Posting to the forum is only allowed for members with active accounts. Please sign in or sign up to post.