04 - Python Variable Types And Objects

4.1 In Python everything is an Object

Basic note for understanding Python Variable Types and Objects is that everything in Python is an object and every object has an ID, Type, and Value. ID is an identifier that identifies a particular instance of an object and interpreter assign it to the object when an object is created. The Type identifies the class of an object and can’t be changed for the life of the object, along with an ID. Value is the content of the object and includes variables, methods and properties object can have. However, it may be or may not be changed during the lifetime of the object. It depends on whether or not the object is mutable (can or can’t change value). Next examples demonstrate the creation of an object and printing its ids. You must accept those things as they are because they work like this and you can’t change it. This is a Python property and behaves in this way.

x = 42
print x, id(x), type(x)
-> 42 5592204 <type 'int'>

x = "string example"
print x, id(x), type(x)
-> string example 37238728 <type 'str'>

ID is generally like an address and depends on how the implementation of your object looks like and is a unique identifier that identifies this particular object. Because everything in Python is an object, it means that the type of x will be some class (every object has its id, class, and value). In those cases, it is an integer (int) or string (str). This is may be unclear to you if you don’t have experience in Object Oriented programming but it will be clear later when we come to Classes.

All variables in Python are first-class objects. That means that if something looks like a very simple variable, it actually may be something more complex. It can be an object that is defined in some library, built-in object or any sort of thing. We will get to it.

So to summarize: in Python, everything is an object and every object has its id, class, and value, no matter what and how it may look like.

4.2 Mutable vs Immutable Objects

As we mentioned, objects can be mutable and immutable (can’t change value). Sometimes it may look like that immutable objects can change the value but this is just optical illusion. Distinguish is visible using id method and you can see that in the example below. Immutable objects in Python are ints, strings and tuples.

x = 42
print x, id(x)
x = 43
print x, id(x)
x = 42
print x, id(x)

->
42 3888268
43 3888256
42 3888268

If you observe little closer the example you can see that if the value of int x is changing, than id of x is also changing. This occurs because the ints in Python are immutable objects. Values are actually references to objects. If the value is changed then the reference is referring to another object. If the value is changed back to the previous value then you can spot that the id is same again, so the variable is referring to the same object. So, to simplify, in this case, we have created two objects with the same name x and those two objects are existing in the memory with the different id. By specifying different value we are just saying the interpreter which one object we’re going to use. This is an important difference and may take a while until you completely understand it.
This will be covered later as we will work with other types. You will find that if you want to change the value of some immutable object, first you have to change the type of that object (to use some mutable type) or to create a new immutable object that will hold the new value. This is how Python works for this kind of stuff.

Most fundamental types are immutable:

  • numbers,
  • strings,
  • tuple

The rest of them are mutable:

  • lists,
  • dictionaries,
  • other objects

4.3 Basic data types in Python

If the term variable is still unclear to you, you can imagine it as the reserved memory location with variable size (depending on the object type), which has a purpose to store values. When you create a variable, it means that you reserved space in memory (1 Byte, 2 Bytes or much more, depending on the object type). Variables do not have to be explicitly declared before assigning a value to it as it should be the case in most other programming languages (C, Java, etc.). So you can simply create a variable just by assigning a value to it. Operator = is used for assigning a value to a variable. From the left side is the variable name and from the right side is the value.

x = 42                creates variable x and value 42 assigned to it, type of x is int
y = "name"         creates variable y and "name" assigned to it, type of y is str

In other programming languages first you have to create a variable and then to assign the value to it, for example:

int x;                      created variable x, type of x is an integer
char y;                   created variable y, type of y is char
char z[];                created variable z which is an array of chars
x = 5;
y = "a";

Created variables can store only the type of values that corresponds to its types, i.e. int can only store integers(numbers), char only characters, etc. In Python that is not a case and you can store in any variable whatever you want and whenever you want. The interpreter will create that variable for you if it is not created yet or is created but has other data type, and it will be of the type that can store values you’re assigning to that variable. This will not be visible to you and you don’t have to take care of it. The only thing you need to do is to write:

variable_name = some_value

Multiple assignments are also possible, but you should avoid them because it is not the PEP8 standard.

x = y = z = 30

In any variable, you can store any kind of value. If you want to change the type of variable you can simply assign a value of some other type to that variable. This may look like to you that you’re doing with the same object, but if you remember what we said above, you will conclude that this is not the same object, but the different object with the same name.

x = 20
print x, id(x), type(x)
x = "name"
print x, id(x), type(x)
->
20 31348116 <type 'int'>
name 30942368 <type 'str'>

Basic Python data types are listed below:

  • Number
  • String
  • List
  • Tuple
  • Dictionary
  • Bool

4.3.1 Numbers

Number data type is immutable data type and can store numeric values. There are 4 different subtypes of Number data type:

  • int (signed integer)
  • float (floating point value)
  • long (long integer, can be represented in hec or oct representation)
  • complex (complex number)

Int

Float

Long

complex

5

5.0

3150L

5.5j

24

-3.2

0x248424L

-62j

81

124.+e10

04846813L

5E+35.7j

 

Table 4.1 Examples of Number Data Types

Long Number type is displayed with the uppercase letter L. Octal representation starts with 0 and hexadecimal with 0x.

A complex number consists of float numbers denoted by x +yj, where the real part is x and imaginary part y.

You can use a principle called cast or explicit conversion to convert one type of number to another.  Methods that you can use to do this are:

  • int(x) - convert x to int
    x = 25.5
    int(x) -> 25          float to int
    y = "123"
    int(y) -> 123        string to int
  • float(x) - convert x to float
    x = 25
    float(25) -> 25.0                int to float
    y = "123.3"
    float(y) -> 123.3                string to float
  • long(x) - convert x to long int
  • complex(x) - convert x to complex with real part x and imaginary part 0
    x = 35
    complex(x) -> (35+0j)    int to complex
  • complex(x,y) - convert to complex with real part x and imaginary part y
    x = 35
    y = 22
    complex(x,y) -> (35+22j)

4.3.2 Strings

Strings in Python are defined as a set of characters between quotes. There are 3 types of quotes used for different things (You can check this in Chapter 3.5). Python has a lot of support and a lot of methods                              incorporated into its core to work with strings. The basic of it is principle called slicing and is very useful. It is used to get only a certain subset of the string, for example, middle of the string, from index 3 to index 7. The          first character in the string has index 0.

        x = "Example string"
        y = "Another example of string"
        print x
        print y
        print x[5]      # prints 6th char
        print x[3:7]   # prints from 3rd to 7th char
        print x[:5]     # prints from the beginning to 5th char
        print x[3:]     # prints from 3rd char to the end
         ->
        Example string
        Another example
        l
        mple
        Examp
        mple string

4.3.3 Tuples

Tuples in Python are defined as one of the most versatile data types. They can hold different items or values, separated by commas and enclosed within parentheses (). Tuples cannot be updated and once they are                    created  there are no more modifications, so they are immutable data type and can be classified as read-only (you can only read from it)

Accessing the values stored in a tuple can be done by using a slice operator [] with index or indexes if you want a certain subset of values from a tuple. Slicing is the same as the slicing of some string, so you can apply all you have learned above.

        x = (5, 25, 13.7, "string_example")            # this is a tuple with 4 elements

        print x           # prints the complete tuple
        print x[3]      # prints 4th element
        print x[1:3]   # prints from 1st to 3rd element
        print x[:3]     # prints from the beginning to 3rd element
         print x[2:]     # prints from 3rd element to the end
         ->
        (5, 25, 13.7, 'string_example')
        string_example
        (25, 13.7)
        (5, 25, 13.7)
        (13.7, 'string_example')

4.3.4 Lists

Lists are similar to tuples and they represent the most versatile Python data type. They can also hold values of different types and the only difference to tuples is that Lists can be updated/modified. You can simply add an      element to list by using append method or modify element by assigning it a different value. List values are separated by commas and enclosed within square brackets [].

        x = [5, 25, 13.7, "string_example"]            # this is a list with 4 elements

        print x           # prints the complete tuple
        print x[3]      # prints 4th element
        print x[1:3]   # prints from 1st to 3rd element
        print x[:3]     # prints from the beginning to 3rd element
        print x[2:]     # prints from 3rd element to the end
         ->
        (5, 25, 13.7, 'string_example')
        string_example
        (25, 13.7)
        (5, 25, 13.7)
        (13.7, 'string_example')

        x = [5, 25, 13.7, "string_example"]
        print x
        x[2] = 10
        print x
        ->
       [5, 25, 13.7, 'string_example']
       [5, 25, 10, 'string_example']

4.3.5 Dictionaries

Dictionaries in Python are some kind of hash table. They are a set of key:value pairs.  Keys can be almost data type, but usually, they are used as strings. Values, from other side, can be any type of object. Key-Value                pairs are separated by commas and enclosed within curly braces {}.To get a specific value from dictionary, you have to specify the key related to that value, when calling the dictionary object.

         x = {"key1":10,
         "key2":25,
         "key3":"some string"}
        print x     # prints the entire dictionary
        print x["key1"] # prints the value assigned to key key1
        print x["key3"] # prints the value assigned to key key3
        ->
        {'key3': 'some string', 'key2': 25, 'key1': 10}
       10
       some string

Because the Python has a lot of implemented methods to support working with strings, tuples, lists and dictionaries, in this tutorial chapters dedicated to mentioned data types were created for your better understanding.        In this chapter, only the basic things are mentioned so you can start working with them, use them a little bit and not to ask questions to yourself if you find list, dictionary, tuple or string in the list example. When we come        to the more advanced stuff everything will be clear to you.

Like us on Facebook