Course
Data Types
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Data Types
Computer is a data processing device. Computer stores the data in its memory and processes it as per the given program. Data is a representation of facts about a certain object.
Some examples of data
Data of students − name, gender, class, marks, age, fee etc.
Data of books in library − title, author, publisher, price, pages, year of publication etc.
Data of employees in an office − name, designation, salary, department, branch, etc.
A data type represents a kind of value and determines what operations can be done on it. Numeric, non-numeric and Boolean (true/false) data are the most obvious data types. However, each programming language has its own classification largely reflecting its programming philosophy.
Python Data Types
Python Data Types are used to define the type of a variable. It defines what type of data we are going to store in a variable. The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:
Python Numeric Data Type
Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example
var1 = 1 # int data typevar2 = True # bool data typevar3 = 10.023 # float data typevar4 = 10+3j # complex data type
Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively
int
(signed integers)bool
(subtype of integers.)float
(floating point real values)complex
(complex numbers)
Python's standard library has a built-in function type(), which returns the class of the given object. Here, it is used to check the type of an integer and floating point number.
>>> type(123)<class 'int'>>>> type(9.99)<class 'float'>
A complex number is made up of two parts - real and imaginary. They are separated by '
+
' or '-
' signs. The imaginary part is suffixed by 'j' which is the imaginary number. The square root of -1 (√−1), is defined as imaginary number. Complex number in Python is represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a complex number.>>> type(5+6j)<class 'complex'>
A Boolean number has only two possible values, as represented by the keywords, True and False. They correspond to integer 1 and 0 respectively.
>>> type (True)<class 'bool'>>>> type(False)<class 'bool'>
Examples
Here are some examples of numbers −
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.a=100print("The type of variable having value", a, " is ", type(a))
# boolean variable.b=Trueprint("The type of variable having value", b, " is ", type(b))
# float variable.c=20.345print("The type of variable having value", c, " is ", type(c))
# complex variable.d=10+3jprint("The type of variable having value", d, " is ", type(d))
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
Python Sequence Data Type
Sequence is a collection data type. It is an ordered collection of items. Items in the sequence have a positional index starting with 0. It is conceptually similar to an array in C or C++. There are following three sequence data types defined in Python.
String
Data TypeList
Data TypeTuple
Data Type
Python sequences are bounded and iterable - Whenever we say an iterable in Python, it means a sequence data type (for example, a list).
Python String Data Type
Python
string
is a sequence of one or more Unicode characters, enclosed in single, double or triple quotation marks (also called inverted commas). Python strings are immutable which means when you perform an operation on strings, you always produce a new string object of the same type, rather than mutating an existing string.As long as the same sequence of characters is enclosed, single or double or triple quotes don't matter. Hence, following string representations are equivalent.
>>> 'TutorialsPoint''TutorialsPoint'>>> "TutorialsPoint"'TutorialsPoint'>>> '''TutorialsPoint''''TutorialsPoint'
A string in Python is an object of str class. It can be verified with type() function.
>>> type("Welcome To TutorialsPoint")<class 'str'>
A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it. However, operations such as slicing and concatenation can be done. Python's str class defines a number of useful methods for string processing. Subsets of strings can be taken using the slice operator (
[ ]
and [:]
) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.The plus (
+
) sign is the string concatenation operator and the asterisk (*
) is the repetition operator in Python. For examplestr = 'Hello World!'
print (str) # Prints complete stringprint (str[0]) # Prints first character of the stringprint (str[2:5]) # Prints characters starting from 3rd to 5thprint (str[2:]) # Prints string starting from 3rd characterprint (str * 2) # Prints string two timesprint (str + "TEST") # Prints concatenated string
This will produce the following result
Hello World!Hllollo World!Hello World!Hello World!Hello World!TEST
Python List Data Type
Python
Lists
are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type.>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]
A list in Python is an object of list class. We can check it with type() function.
>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list object can also be an item in another list. In that case, it becomes a nested list.
>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]
A list
can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined class also.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tinylist = [123, 'john']
print (list) # Prints complete listprint (list[0]) # Prints first element of the listprint (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd elementprint (tinylist * 2) # Prints list two timesprint (list + tinylist) # Prints concatenated lists
This produce the following result
['abcd', 786, 2.23, 'john', 70.2]abcd[786, 2.23][2.23, 'john', 70.2][123, 'john', 123, 'john']['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
Python Tuple Data Type
Python
tuple
is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses (...
).A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the collection. The index starts from 0.
>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)
In Python, a tuple is an object of tuple class. We can check it with the type() function.
>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))<class 'tuple'>
As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python class.
>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))
To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing symbols are treated as a tuple by default.
>>> 2023, "Python", 3.11, 5+6j, 1.23E-4(2023, 'Python', 3.11, (5+6j), 0.000123)
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed .ie lists are mutable, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as read-only lists. For example −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )tinytuple = (123, 'john')
print (tuple) # Prints the complete tupleprint (tuple[0]) # Prints first element of the tupleprint (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:]) # Prints elements of the tuple starting from 3rd elementprint (tinytuple * 2) # Prints the contents of the tuple twiceprint (tuple + tinytuple) # Prints concatenated tuples
This produce the following result
('abcd', 786, 2.23, 'john', 70.2)abcd(786, 2.23)(2.23, 'john', 70.2)(123, 'john', 123, 'john')('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tuple[2] = 1000 # Invalid syntax with tuplelist[2] = 1000 # Valid syntax with list
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
Python Ranges Function
Python range() is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers. Following is the syntax of the function:
range(start, stop, step)
Here is the description of the parameters used:
- start: Integer number to specify starting position, (Its optional, Default: 0)
- stop: Integer number to specify starting position (It's mandatory)
- step: Integer number to specify increment, (Its optional, Default: 1)
Examples
Following is a program which uses for loop to print number from 0 to 4
for i in range(5): print(i)
This produce the following result
01234
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5): print(i)
This produce the following result
1234
Again, let's modify the program to print the number starting from 1 but with an increment of 2 instead of 1:
for i in range(1, 5, 2): print(i)
This produce the following result
13
Python Dictionary Data Type
Python
dictionaries
are kind of hash table type. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.Python dictionary is like associative arrays or hashes found in Perl and consist of key:value pairs. The pairs are separated by comma and put inside curly brackets {}. To establish mapping between key and value, the semicolon':' symbol is put between the two.
>>> {1:'one', 2:'two', 3:'three'}
In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.
>>> type({1:'one', 2:'two', 3:'three'})<class 'dict'>
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example
dict = {}dict['one'] = "This is one"dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' keyprint (dict[2]) # Prints value for 2 keyprint (tinydict) # Prints complete dictionaryprint (tinydict.keys()) # Prints all the keysprint (tinydict.values()) # Prints all the values
This produce the following result
This is oneThis is two{'dept': 'sales', 'code': 6734, 'name': 'john'}['dept', 'code', 'name']['sales', 6734, 'john']
Python's dictionary is not a sequence. It is a collection of items but each item (key:value pair) is not identified by positional index as in string, list or tuple. Hence, slicing operation cannot be done on a dictionary. Dictionary is a mutable object, so it is possible to perform add, modify or delete actions with corresponding functionality defined in dict class. These operations will be explained in a subsequent chapter.
Python Set Data Type
Set
is a Python implementation of set as defined in Mathematics. A set in Python is a collection, but is not an indexed or ordered collection as string, list or tuple. An object cannot appear more than once in a set, whereas in List and Tuple, same object can appear more than once.Comma separated items in a set are put inside curly brackets or braces {}. Items in the set collection can be of different data types.
>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}{(5+6j), 3.11, 0.000123, 'Python', 2023}
Note that items in the set collection may not follow the same order in which they are entered. The position of items is optimized by Python to perform operations over set as defined in mathematics.
Python’s Set is an object of built-in set class, as can be checked with the type() function.
>>> type({2023, "Python", 3.11, 5+6j, 1.23E-4})<class 'set'>
A set can store only immutable objects such as number (int, float, complex or bool), string or tuple. If you try to put a list or a dictionary in the set collection, Python raises a TypeError.
>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'
Hashing is a mechanism in computer science which enables quicker searching of objects in computer's memory. Only immutable objects are hashable.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence, add/delete/update operations are permitted on a set object, using the methods in built-in set class. Python also has a set of operators to perform set manipulation. The methods and operators are explained in latter chapters
Python Boolean Data Types
Python boolean type is one of built-in data types which represents one of the two values either True or False. Python bool() function allows you to evaluate the value of any expression and returns either True or False based on the expression.
Examples
Following is a program which prints the value of boolean variables a and b
a = True# display the value of aprint(a)
# display the data type of aprint(type(a))
This produce the following result
true<class 'bool'>
Following is another program which evaluates the expressions and prints the return values:
# Returns false as a is not equal to ba = 2b = 4print(bool(a==b))
# Following also prints the sameprint(a==b)
# Returns False as a is Nonea = Noneprint(bool(a))
# Returns false as a is an empty sequencea = ()print(bool(a))
# Returns false as a is 0a = 0.0print(bool(a))
# Returns false as a is 10a = 10print(bool(a))
This produce the following result
FalseFalseFalseFalseFalseTrue
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.