In this tutorial, we will discuss the required Python data types. It will help you know what options you have in Python.
Python is a type-free language and follows dynamic data binding, i.e., when writing the program, the programmer does not need to declare data type explicitly. The compiler/interpreter decides the type of data during execution.
What is Data types in Python
Data types are used in Python to classify a particular type of data. It is important because the specific type of information you use will determine which values you can assign and what you can do. Every Python value has a datatype. In Python programming, everything is an object, data types are classes, and variables are instance (object) of these classes.
Data types enable a compiler to allocate the correct space for a variable and check the type, ensuring the program uses the variables according to the defined type. Python allows us to check the variable type used in the program. Python gives us the function type() that returns the type of the variable passed. The isinstance() function is also used to check whether an object belongs to a specific class.
Consider the following example to define and check the values of different data types.
a = 5 b = "Hi Python" c = 5.5 d = 1+2j print(type(a)) print(type(b)) print(type(c)) print(d, "is complex number?", isinstance(1+2j,complex))
Output:
There are several data types in Python. Let’s take a look at the data types in Python.
Scalar Data Types in Python
Scalar data types store single numbers, boolean, and character, while composite types store multiple values, e.g., recording and collecting. In Python, the most commonly used scalar types are:
Boolean Data Type
There are two built-in Boolean data types in Python: True or False, and the Python type is Bool. These values are used in conditions, comparisons, and structures that require the representation of truth or falsehood.
To show how Boolean data types function, create three variables that contain boolean values from the assigned expressions.
bool_a = (15 >= 9) bool_b = (15 == 5*5) bool_c = (10 != 5*6)
Use the print function to see the values stored in each variable:
print(bool_a, bool_b, bool_c)
Number Data Types
Python has three numerical data types: integers, floats, and complex numbers fall into the Python numbers category. They define as int, float, and complex classes in Python. They are immutable data types, meaning that a new object changes the value of several data types.
Python can tell whether the number is an integer or float due to a decimal point presence or absence. By its standard form a + bj, it recognizes a complex number. Therefore a number should not be declared as a specific type.
message = "Hi ComputerNote" num = 5 pi = 3.14159 cmp = 2+5j print(message, "is of type", type(message)) # This return a string print(num, "is of type", type(num)) # This will return an integer print(pi, "is of type", type(pi)) # This will return a float print(cmp, "is complex number?", isinstance(1+2j,complex))
Sequence Data Type in Python
A sequence is an ordered collection of similar or different types of data. The following integrated sequence data types are available in Python:
Python List
An ordered list object is a collection of series of values. It is one of the most commonly used and highly flexible data types in Python. Not all items in a list of the same type.
It is quite straightforward to declare a list. Comma-separated items are included in brackets [].
a = [1, 1.1, 'Computers']
All lists in Python are zero-based indexed. When the member or the length of a list is referenced, the number of list elements is always the number plus one.
a = [15,20,25,30,20,10,25,10]
You can assign data to a particular element of the list using an index. The index of the list begins at zero. The data can be allocated as follows to the elements of an array:
print("a[3] = ", a[3]) print("a[0:5] = ", a[0:5]) print("a[4:] = ", a[4:])
Output :
Python Tuple
A tuple is an ordered sequence of items, like a list. The only difference is that tuples are immutable. Tuples can not be modified once they have been created.
Tuples are used to write protection data and are usually faster than lists since they cannot dynamically change.
Tuples are defined by parenthesis () where commas separate items.
t = (Computers,'96', 1+4j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = ('Computers',96, 1+4j) print("t[1] = ", t[1]) print("t[0:3] = ", t[0:3])
Output:
Here are some advantages of tuples over lists:
• Tuples have no append or extend method. • Unable to remove elements from a tuple. • Elements can be found in a tuple, as this does not change the tuple. • The in-operator can also be used to check whether an element exists in the tuple. • Tuples are faster than lists. When defining a constant set of values and everything you ever do with it is to iterate through it, use a tuple rather than a list. • Your code becomes more secure if you 'write-protect' data that need not be changed.
Python Strings
String is sequence of Unicode characters. We can use single, double or triple quotes to represent strings. Multi-line strings can be denoted using triple quotes, ”’ or “””.
str = "String is sequence of Unicode characters" print(str) str = '''String is sequence of Unicode characters''' print(str)
Output :
Python can format multiple strings and numbers using a special syntax. The string format is quickly covered here because it is often seen and the syntax must recognize.
print "The item {} is repeated {} times".format(element,count))
The {} is a placeholder that is replaced by the element of the variables and count in the final string—this compact syntax designed to keep the code readable and compact.
Set Data Types in Python
Python Set
Set is a mutable collection of unique items that is unordered. The set is defined by values that are separated by a comma within { } braces. A set object has appropriate methods to perform mathematical set operations such as union, intersection, difference, etc.
s = {15,20,30,11,41} print("as = ", s) print(type(s))
Output :
Mapping Data Types in Python
Python Dictionary
Dictionary Dict() in Python is a list of Key: value pairs that are unordered. It is a very powerful data type that contains much-associated information that can be associated with keys. A dictionary’s primary function is to extract a value based on the key name. In contrast to lists in which index numbers use, dictionaries allow you to access a key. Dictionaries can also be used for sorting, iterating and comparing data.
d = {1:'value','key':2} print(type(d)) print("d[1] = ", d[1]); print("d['key'] = ", d['key']);
Output :
Mutable and Immutable Types
Data objects of the above types stores in a computer’s memory for processing. Some of these values can change during processing, but others’ contents cannot change once in the memory they are created.
Numbers, strings, and tuples are immutable, so their contents cannot change after they are created.
Items in a list or dictionary object can be modified. It is possible to add, delete, insert, and rearrange items in a list or dictionary. They are mutable objects.