Python online tutorial

Part 6: Types

When you create a variable in Python, it is automatically assigned a type. The type of a variable determines, for example, what you can compare it with – the interpreter will complain if you try and order a list comprised of both strings and numbers. Note the amount of space assigned to a variable in memory also depends on this property – a list, for example, gets a much larger chunk than a character. Here are the most common variable types used in Python:

  • int, short for integer, a numerical type used to represent whole numbers, eg. 0, 672 or -5.
  • float, short for floating-point, another numerical type used when we want more precision, used to represent real numbers. Examples: 2.5, 3.1415926535, 1.02e8 (note the type supports scientific notation).
  • boolean, a type that can take only two values: True or False (note the capitalized words), with the obvious meaning.
  • string, a sequence of characters such as 'Hello World!'. Note Python doesn’t really care if you use single ' or double " quotes as long as you are consistent.
  • list, the simplest data structure – you might know them as arrays in other programming languages. Each element is assigned an index, which starts from 0 for the first element and successive integers for the next elements. Take a look at the example below to understand the syntax.
  • tuple – a sequence similar to a list. The difference is once you create a tuple, you cannot change its value – they are immutable. Example uses include coordinates and RGBA colours (see below). They are most commonly used as pairs or triplets, but you can have a tuple of whatever length you want.
  • dictionary, an arbitrarily long list of key-value pairs. In other words, a dictionary is a mapping from one item (the key) to another (the value), just like in a real dictionary you have a word and a definition. This mapping can be done via a predefined function or using any other criteria we can think of, including none at all.

We will be looking only at the ones in this list, but a full list of types can be found here: docs.python.org/3/library/stdtypes

A word of advice, however: the above link contains every single type in the Python language, including byte-level constructs usually not necessary for the inexperienced programmer. Don’t let this confuse you – if there is an easier way, you should use that instead.

If you really don’t want to give a type to your variable when you create it, you can assign it to None, but there’s a good chance you won’t need this for years of coding in Python.

Now, let’s take a look at some examples before you can move on.

Examples

Try this