Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Variables in Python: Summary

In this course, you covered the basics of Python variables, including object references and identity, and naming of Python identifiers. You now have a good understanding of some of Python’s data types and know how to create variables that reference objects of those types.

Download

Course Slides (PDF)

1.0 MB

Take the Quiz: Test your knowledge with our interactive “Variables in Python: Usage and Best Practices” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Variables in Python: Usage and Best Practices

In this quiz, you'll test your understanding of variables in Python. Variables are symbolic names that refer to objects or values stored in your computer's memory, and they're essential building blocks for any Python program.

00:00 All right! To wrap up this course, let’s go quickly over the most important takeaways that we talked about.

00:08 First of all, variable assignment. It looks like this in Python. It’s very simple. On the left side you put the name of the variable, an equal sign (=), and then the value.

00:17 That’s just how it works in Python. And what it does is it creates a reference from a name to an object that gets created in memory. All right. So, I mentioned the term object.

00:29 What I want you to take away is that everything is an object in Python, be it a string, an integer, an object that you create yourself, or even a function.

00:37 Everything’s an object. And with the variables, you’re pointing to different objects in memory.

00:44 Then we talked about something surprising in Python which is explained by the fact that Python caches small integers for performance improvements. And there’s also a little challenge that I suggest you to do if you haven’t done it yet.

00:57 Just get your brain to think about it, it’s a fun thing, and it’s something that you can challenge your friends with as well. Next, we looked at variable naming conventions.

01:04 We said that variables can have any length. They can be very short or very long. They can be upper or lowercase characters or a mix of both, but take care with mixing them. The snake is watching you, ha. Generally, you want to use snake case. That is a mix of lowercase characters and underscores (_). Therefore, underscores are fine to be used.

01:23 You can use digits inside of your variables, but you cannot use the digits at the beginning or just only digits. That’s not okay in Python. And since Python 3, also Unicode characters are supported. And finally, we took a look at reserved keywords in Python and the quickest and easiest way to get help on what those are is to type in help() and the string "keywords", and Python’s going to print you out a list of the keywords that you cannot use as variable names because they have a special meaning in Python. And that wraps it up!

01:56 I hope you had fun in this course and that you learned something. See you in the next one!

Avatar image for derekm

derekm on Dec. 10, 2019

Good overview. Reinforced a couple of things for me.

Avatar image for princer800

princer800 on Dec. 13, 2019

Enjoyed it and good explanation on how Python handles variable objects. DO see some variation from course between Windows and Linux versions.

Avatar image for Asif

Asif on Dec. 14, 2019

This stuff is really helpful… thank you!

Avatar image for Adrian

Adrian on Jan. 29, 2020

Was unaware of small integer caching … thx!

Avatar image for Martin Breuss

Martin Breuss RP Team on Jan. 29, 2020

Glad that you’ve enjoyed it and happy if it’s been helpful :)

Avatar image for emalfiza

emalfiza on Feb. 27, 2020

Martin B, totally enjoyed learning new stuffs from your course.

Avatar image for Sandro

Sandro on March 2, 2020

The snake is… ever watchful!

Nice intro on small integer caching. Hoping that I understood it right, all those integers are automatically instantiated as objects and remain so for the entire session, never to be garbage-collected?

Seeing it another way, is Python “encouraging” us to use those numbers throughout the program (e.g. if I need to refer to the figure of 10000, then try to use 10 throughout the code, then adjust the final figure by x 1000? Or is that not a concern?

Thank you,

Avatar image for Martin Breuss

Martin Breuss RP Team on March 5, 2020

This is a great question and I don’t have a great answer for it myself. I can tell you that for any program you are likely to write at the beginning of your programming journey (and probably way into it as well, tbh) it doesn’t matter.

I’m sure that there are applications that need to really edge out speed and memory usage in order to perform, especially when handling huge amounts of data. However, it is likely that if speed and memory-lookup performance is that important for your app, your company might use a different programming language altogether, since that is not Python’s main area of strength.

There’s an interesting answer on StackOverflow with a ton of links that can lead you onwards, if you want to learn more about this topic. It doesn’t specifically go into Python, but you might still find something enlightening in there. Hope that helps a little and keep on investigating! :D

Avatar image for Sandro

Sandro on March 5, 2020

Thank you, Martin! Yes that is exactly what I was thinking of: memory usage and speed. You’re right, Python is considered a slower language than its counterparts like C++. Will check the link you posted. :)

Avatar image for kingjay2498

kingjay2498 on March 12, 2020

Hello my name is Jay , new to coding an really enjoy the course , lesson was detail an clear . Will continue to study an learn more .

Avatar image for markthiele

markthiele on March 16, 2020

Thanks, helps a lot!

Avatar image for avalidzy

avalidzy on April 6, 2020

Of what constitutes an “object” in terms of variables. Apparently small integers from -5 through 256 are a special class of objects.

Avatar image for Martin Breuss

Martin Breuss RP Team on April 6, 2020

Hi @avalidzy. Small integers are normal objects like any other object is an object in Python. The “special” thing about them is only that Python doesn’t create a new instance of an object (= a new object) each time you reference an integer in that range. Instead it refers to that integer object that already exists. It’s a performance thing, but doesn’t make small integer objects special in any way. Hope that makes sense!

Avatar image for avalidzy

avalidzy on April 6, 2020

Thanks for clarifying the nature of a python object! ;)

Avatar image for pshapard

pshapard on April 21, 2020

Thanks for this video. It was helpful. Onto the next video.

Avatar image for jeffgorzen

jeffgorzen on May 3, 2020

Could you show how to set a data type at input like a = 39 {int8}?

Avatar image for Martin Breuss

Martin Breuss RP Team on May 4, 2020

Hi @jeffgorzen. Python is a dynamically typed language, which means you don’t declare the data type of variables when you declare them. The interpreter figures it out at runtime.

You can read more about some more recently introduced ways of adding type checking functionality in the Python Type Checking article.

Avatar image for Konstantin Schukin

Konstantin Schukin on June 19, 2020

Thank you, Martin, for the good and clear lessons.

Avatar image for Alain Rouleau

Alain Rouleau on July 26, 2020

Really enjoyed the course, thanks!

Avatar image for Deepak Reddy

Deepak Reddy on Dec. 3, 2020

Great reference about variables. I had initially read the supporting material to under the concepts . There are few topics which confused me but after watching the video course its crystal clear now :-).

Avatar image for Greish

Greish on Dec. 3, 2020

Great course! Enjoyed every lesson of it!

Avatar image for Martin Breuss

Martin Breuss RP Team on Dec. 3, 2020

Hi all! Glad you’ve found the course useful :D

Avatar image for roodee

roodee on Feb. 12, 2021

Thank you for this course, Martin.

#1 takeaway for me is the small integer cache, which was something completely unknown for me. Consequently I also liked the python pub quiz referring to it.

#2 is the keyword package. Seems useful.

Perhaps something to add to the course: Usage (and caveats) of comparison operators == and is ?

Avatar image for Shahad Sidek

Shahad Sidek on April 23, 2022

Learned few things and refreshed a bit of what i know.. thank you

Avatar image for rwelk

rwelk on Jan. 29, 2024

Found out that I need to use help(dir) a lot more than I currently do. This is my take away from the lesson.

Avatar image for Martin Breuss

Martin Breuss RP Team on Jan. 30, 2024

Glad the course has been useful :D

And yes, I think you mean that using both help() and dir() can really be very helpful for learning more about the objects that you’re working with!

Avatar image for AndersC

AndersC on Aug. 26, 2024

Great lecture. Thanks!

One thing that made me a bit confused concerning the challenge example. It seems you get different results depending on how you assign the values to the variables. Check the following run:

In [38]: e = 258

In [39]: f = 258

In [40]: id(e)
Out[40]: 1806617088784

In [41]: id(f)
Out[41]: 1806617092816

In [42]: if e is not f:
    ...:     print('They are not the same')
    ...: else:
    ...:     print('They are the same')
    ...:
They are not the same

In [43]: g, h = 258, 258

In [44]: if g is not h:
    ...:     print('They are not the same')
    ...: else:
    ...:     print('They are the same')
    ...:
They are the same

In [45]: id(g)
Out[45]: 1806613750640

In [46]: id(h)
Out[46]: 1806613750640
Avatar image for Martin Breuss

Martin Breuss RP Team on Aug. 26, 2024

@AndersC that’s a great observation! Indeed, Python handles situations differently whether you use two separate assignment statements, or a simultaneous assignment statement. In the latter case, it’ll apply some optimizations.

You can use the dis module to dig deeper and find out how Python handles them under the hood. It allows you to see the bytecode instructions that Python generates for a function:

>>> import dis

>>> def separate_assignments():
...     e = 258
...     f = 258
...     return e is f
...

>>> dis.dis(separate_assignments)
  1           0 RESUME                   0

  2           2 LOAD_CONST               1 (258)
              4 STORE_FAST               0 (e)

  3           6 LOAD_CONST               1 (258)
              8 STORE_FAST               1 (f)

  4          10 LOAD_FAST                0 (e)
             12 LOAD_FAST                1 (f)
             14 IS_OP                    0
             16 RETURN_VALUE

The exact meaning of all the instructions isn’t that relevant, but still, here’s what a couple of them mean:

  • LOAD_CONST 1 (258): The value 258 is loaded as a constant twice—once for each assignment to e and f.

  • STORE_FAST 0 (e) and STORE_FAST 1 (f): These instructions store the loaded constant into the local variables e and f.

  • IS_OP 0: This checks whether e and f refer to the same object in memory.

Here, Python loads the constant 258 twice, meaning that e and f could potentially be stored in different memory locations if Python doesn’t optimize the memory usage, leading to e is f being False.

Now, when you try the other approach you get different bytecode instructions:

>>> def simultaneous_assignment():
...     g, h = 258, 258
...     return g is h
...

>>> dis.dis(simultaneous_assignment)
  1           0 RESUME                   0

  2           2 LOAD_CONST               1 ((258, 258))
              4 UNPACK_SEQUENCE          2
              8 STORE_FAST               0 (g)
             10 STORE_FAST               1 (h)

  3          12 LOAD_FAST                0 (g)
             14 LOAD_FAST                1 (h)
             16 IS_OP                    0
             18 RETURN_VALUE

As you can see, the bytecode instructions are different than before.

  • LOAD_CONST 1 ((258, 258)): This line shows that Python is loading a tuple containing the two instances of 258 as a constant. Python has created a tuple ((258, 258)) and loaded it as a single constant.

  • UNPACK_SEQUENCE 2: This instruction unpacks the tuple into two separate elements. It effectively splits the tuple (258, 258) into its two components.

With this setup, Python optimizes the assignment by packing the values (258, 258) into a single tuple and then unpacking them into the variables g and h. This is efficient because Python recognizes that the same value (258) is being assigned twice and therefore optimizes by reusing the object where possible.

Because of this optimization, both g and h likely refer to the same object in memory.

Avatar image for AndersC

AndersC on Aug. 27, 2024

Thanks for the explanation! It makes sense.

Avatar image for rweintr

rweintr on Sept. 25, 2024

It seems like strings are cached as well in Python. If I assign a=”cat” and b=”cat”, I get True for a is b. I expected that a separate object would be created for each assignment. Interestingly, if you embed a space in your string like a=”cat dog” and b=”cat dog”, Python does create separate objects ie. a is b is False.

Avatar image for Martin Breuss

Martin Breuss RP Team on Sept. 26, 2024

@rweintr good find! Python indeed does something similar with small common strings. It’s called string interning. Python does that automatically with strings that may reasonably appear more often in a program, e.g. short strings or strings that may be used as identifiers.

You can also explicitly intern a string, if you think that this (minor) performance boost may be relevant:

>>> import sys
>>> a = sys.intern("cat dog")
>>> b = sys.intern("cat dog")
>>> a is b
True
Avatar image for MarekO

MarekO on Nov. 5, 2024

Very interesting tutorial, When I thought there possibly might nothing else to learn about variables :)

takeaways for me:

  • Small integer caching
  • Keyword search
  • Interesting points from other user’s comments

Thanks alot

Become a Member to join the conversation.