Data types in Python 3
Introduction
In this post we will have a look at several built-in data types in Python, like numbers, strings, lists and others. I will use Ubuntu 18.04 with Python 3.5.2 for demonstration, but you can use any Python 3 interpreter, for example Python IDLE for Windows or MacOS.
$ python3 Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Data Types
Variables in Python don’t have to be explicitly declared, therefore the data type of a variable is determined automatically by Python interpreter based on the assigned value. We can use built-in type function to determine the type of a variable.
Numbers
There are four types of numbers in Python: integers, floats, complex numbers and Booleans.
Integers
Integers are whole numbers (either positive or negative) and zero.
Examples: -456343, -4 , 0 , 23, 9942323232
In the example below we assign value 10 to a variable “n” and then check its data type by using function type :
>>> n = 10
>>> n
10
>>> type(n)
<class 'int'>
>>>
Floats
Float numbers represent real numbers, which have both integer and fractional parts. They can also be represented using scientific notation, for example 4e-3 (0.004).
Examples: -0.00258, 0.1, 15.2, 78.569, 1e12
In the example below we assign the value 4e-3 to a variable “f” and then we see that it has a data type of float
>>> f = 4e-3 >>> f 0.004 >>> type(f) <class 'float'> >>>
Complex Numbers
Complex numbers contain both real and imaginary part.
Complex number in Python have the following format a+bj, where a and b are real numbers.
>>> i = 3-4j >>> i (3-4j) >>> type(i) <class 'complex'>
Booleans
Booleans are logical variable which can be equal either to True or False.
They may also be represented by 1 and 0. In this case 1 is equal to True and 0 is equal to False. We set variable b to True and then see that it is also equal to 1.
>>> b = True >>> b == 1 True >>> b == 0 False
Lists
Lists can contain variables of different data types, for example a mixture of numbers, strings and even other lists. Lists are somewhat similar to arrays in other programming languages.
Let’s create a list containing numbers, strings and another list:
>>> l = ["the first", -4, 5.6 , 4+2j, ["a", "b"], "the last"] >>> l ['the first', -4, 5.6, (4+2j), ['a', 'b'], 'the last'] >>> l[0] 'the first' >>> l[-1] 'the last' >>> l[4] ['a', 'b'] >>> type(l) <class 'list'>
In the example above we have created a list containing 6 elements. We define list elements in square brackets, separated by commas. The first and the last elements are strings, the second element from the end is another list, the remaining items are numbers.
As you can see in the code listing we can refer to the elements of the list using their indices. List indexing starts from zero, therefore the first element is accessed using index 0, like this:
>>> l[0] 'the first'
The next element in the list will have index of 1 and so on till the end of the list.
It is worth mentioning that we can also use negative numbers for referring to lists’ elements. In this case elements count from the end and start counting from -1, that is the last element has index -1:
>>> l[-1] 'the last'
Tuples
Tuples are similar to lists, because they also contain other items. The difference is that tuples are immutable, that is you can’t modify the values of its elements.
>>> t = ("the first", -4, 5.6 , 4+2j, ["a", "b"], "the last") >>> t[0] 'the first' >>> type(t) <class 'tuple'> >>> t[0] = "the new first" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>>
As shown in the example above we get an error when we try to change the value of an element of a tuple. Tuples are not as flexible as lists, but they are more efficient, therefore they are usually used when their content is not going to be modified.
Strings
Strings in Python are also immutable. They are usually defined using single or double quotes. This make it possible to have quote symbols in strings as you will see in the following examples. Let’s create a simple string:
>>> s = 'a simple string'
Now, if we want to have a quote symbol somewhere in the string, we need to use the double quotes when defining the string, otherwise the interpreter will not know where the string starts and where it ends:
>>> s = "Let's learn some Python"
Dictionaries
Dictionaries provide an associative array functionality, that is they contain key-value pairs and allow us to get a value based on a key. Values can be of any data type, but keys must be of an immutable type(numbers, strings or tuples).
>>> dict = {"one":"first", "two":"second", "three":"third"} >>> dict["one"] 'first' >>>
Sets
Sets are unordered collections of objects. They are mostly used when it is required to check whether an item belongs to a particular set or not. Sets can’t contain duplicates, because it makes no sense. Let’s look at an example, where we create a set from a list:
>>> s = set(['one','two','four']) >>> s {'one', 'four', 'two'} >>> 'four' in s True >>> 'three' in s False
As you can see we have created a set of three elements. Then we check whether ‘four’ and ‘three’ are in our set and we get correct results. We could have also defined the set using curly braces like this:
>>> s = {'five','four','six'} >>> type(s) <class 'set'> >>>
File Objects
File objects are used for accessing files.
First, we have to create a file object using open function, which takes two parameters: filename and access mode.
Access modes:
“r”- read only
“w” – write only
“w+” – write and create a file if it does not exist
“r+” – both read and write access
“x” – create a file
Once we have a file object we can read and write to it. File objects have the following methods for doing this:
readline() – reads a single line from a file. Returns a string
write() – writes a string to a file. Returns the number of characters written to a file
After we have finished working with file we have to close it by calling close() method of a file object.
Let’s create a new file and write two lines to it:
>>> import os >>> os.getcwd() '/home/orkhans' >>> f = open('newfile', 'w+') >>> f.write('Hello!\n') 7 >>> f.write('This is the second line.\n') 25 >>> f.close()
The first two lines are not necessary, I have used them to make sure I was in a proper directory. os module contains getcwd() function which returns the current working directory.
First we create a file supplying its name and the access mode. Then we call write() function two times and each time it returns the number of written characters. Then we close the file.
Now, let’s open this file again and read its contents;
>>> f = open('newfile', 'r') >>> line = f.readline() >>> print (line) Hello! >>> line = f.readline() >>> print (line) This is the second line. >>> f.close()
readline() function returns a string reading a single line from a file. We can assign the returned value to a variable. After we finish working with our file we close it.
Conclusion
This was the basic overview of data types in Python 3. Thank you for reading:)