DEV Community

Cover image for Mastering Datatypes in Python
Mcvean Soans
Mcvean Soans

Posted on

Mastering Datatypes in Python

This topic might be a bore for non-enthusiasts and beginners alike 😕, but really is quite easy and simple to pick up 🤭. Okay, before you criticize me for my demeanor, let me make it clear that the aim of this post is to strengthen the fundamentals of beginners, and for the experienced folks to brush up on their amazing skills!

A datatype, simply put, represents the type of data stored into a variable, in memory. These may be classified into 2 main categories: Built-in and User-defined. For now, let us focus on built-in datatypes only.

Built-in Datatypes

Python provides a few built-in data types, which come preloaded when it is installed:

  • None
  • Numeric
  • bool
  • Sequences
  • Sets
  • Mappings (Dictionaries)

Let us look at each of these in detail! 😄

None Type

In Python, the 'None' datatype represents an object which does not contain any value (similar to 'null' in Java). Python being a dynamically-typed language, 'None' is used less frequently.

Numeric Type

These represent numbers, and are further subdivided into:

  1. int - These represent integers (a number without any decimal point). For example, a = -30 or b = 289.

  2. float - These represent floating-point numbers (a number containing a decimal point). For example, n = 25.69 or x = 30.26e3, where 'e' or 'E' represents exponentiation to the power of 10.

  3. complex - These represent complex numbers written in the form a+bj or a+bJ. In this form, 'a' is the real part of the number and 'b' is the coefficient, while 'j' or 'J' is the square root of -1. For example,
    c1 = 1 - 0.5j or c2 = 2 + 5J.

🤔 You may find this interesting too :
Python provides facilities to represent Binary, Octal and Hexadecimal numbers too. A binary number should be written with a prefix '0b' (zero and b) or '0B' (zero and B), octal numbers with a prefix of '0o' (zero and o) or '0O' (zero and O), and hexadecimal numbers with a prefix of '0x' (zero and x) or '0X' (zero and X).

bool Type

This is a special datatype which represents either "True" or "False". It is used mainly in conditional statements to evaluate conditions and provide a logical answer (True or False). Conditional statements will be covered in an upcoming post, but for now we only need to know that they help us decide the flow of control of our program depending on any given condition.

Sequences in Python

These may be looked at as a group of elements or items. In Python, we have six types of sequences:

  1. str - These represent strings (a group of characters) in Python. Strings are enclosed within double or single quotes, and even with triple double quotes or triple single quotes (called docstrings). For example,
    word = "Hello" or name = "Mack".

  2. bytes - These represent a group of byte numbers just like an array. A byte number is any positive number from 0 to 255 (inclusive). For example, x = bytes([0, 10, 20, 30, 40, 50]) creates a bytes array having 6 elements.

  3. bytearray - This is exactly similar to the bytes datatype, the only difference being that this datatype is mutable (the elements of an array, once created, cannot be altered). We will look at mutability later on so do continue reading! 😁

  4. list - Lists in Python are similar to arrays in C or Java, the main difference being a list is capable of storing multiple types of objects, whereas an array can only store one type of elements. Hence, we can see that lists are a very important datatype. For example,
    names = ['John', 'Roy', 'Michelle', 'Sharon'] or
    misc = [1, 'Michael', 23.60, -30].

  5. tuple - A tuple is exactly similar to a list, the only main difference being that a tuple is immutable whereas a list is mutable. Hence, we can say that a tuple is a read-only list. For example,
    names = ('John', 'Roy', 'Michelle', 'Sharon') or
    misc = (1, 'Michael', 23.60, -30).

  6. range - These represent a sequence of numbers. Similar to a tuple, the elements are not modifiable i.e., this datatype is immutable. These are generally used in loops and iterative structures. For example,
    r = range(10), the variable 'r' stores numbers from 0 upto 9.

🤔 A key takeaway :
From the above examples, we can see that a list encloses elements within opening and closing square / box brackets ('[' and ']'), while a tuple encloses elements within opening and closing parenthesis ('(' and ')').

Sets in Python

A set is an unordered collection of elements. What does this mean? Well, whenever we create a sequence in Python, the order of the elements stays put (fixed). This is not true for sets. Whenever we create a set, the elements may not appear in the same order as they are entered. Moreover, a set does not accept duplicate elements. Sets are again sub-divided into two:

  1. set - This is similar to an array and uses opening and closing curly brackets ('{' and '}') to store the elements. We can create a set in two ways, for example, s1 = {1, 2, 3, 4, 5} or s2 = set("Hello"). The second method utilizes the 'set( )' function to convert the letters of the string into a set.

  2. frozenset - It is similar to the set datatype, the only difference being, frozenset datatype as the name suggests is immutable, while the set datatype is mutable. We also have two ways to create a frozenset, we can first create a set and then pass it thorugh the frozenset( ) function fs1 = frozenset(s1) or directly pass another object (such as a string) to create a frozenset, fs2 = frozenset("Hello").

Mappings (Dictionaries) in Python

A map represents a group of elements in the form of key-value pairs. Understanding dictionaries in Python is pretty simple.

Imagine you are given a particular word (say "Photosynthesis") with a dictionary in hand, and you are said to locate the meaning of the word using the dictionary. Logically, we would start searching for the meaning, by first looking up the letters (starting from the first all the way upto the last one) until we find the word (starting from "P" in our case, followed by "h", "o", and all the way upto "s"). This way, we are able to quickly locate the meaning without having to look at the meaning of each and every word in the dictionary. In this case the word is considered as the "key" and the meaning is considered as the "value"

Similarly, the 'dict' datatype in Python is utilized to store key-value pairs. The keys and values are separated using a colon (:) and every key-value pair is separated using a comma (,). Finally, all the elements are to be enclosed within curly brackets ({ }).

Also, dictionaries are mutable and hence the elements stored in the dictionaries can be altered. For example,
roll = {1: "Aaron", 2: "Adele", 3: "Mike", 4: "Ryan"} or d = {} is an empty dictionary.

Mutability

It is a property of an object by which it's elements can be altered after creation. Let us take a look at the following code:

lst = [1,2,3,4,5] # A list of 5 elements
print(lst) # [1,2,3,4,5] is printed
lst[0] = 10 # Changing value at index 0
print(lst) # [10,2,3,4,5] is printed
Enter fullscreen mode Exit fullscreen mode

From the above code, we can make out that the value of the first element in the list (at index 0) was changed from '1' to '10'. We were able to do this because as we have seen earlier, lists are mutable. Finally, let us look at another example:

tup = (1,2,3,4,5) # A tuple of 5 elements
tup[0] = 10 # Throws an error on the screen
Enter fullscreen mode Exit fullscreen mode

As we can see, the second statement throws an error. Why is that? It is because tuples (similar to frozenset and bytes) are immutable. Any attempt to alter the elements, once the object has been created, is simply not allowed.

Top comments (0)