﻿ Python Basics: Data types | Startxlabs

Python Basics: Data types

By StartxLabs
Date 22-04-21 " Python Basics: Data types"

Python is an object-oriented, interpreted programming language that is simple and easy to use that has significant applications in software development, web development, data science, and so on. The first thing you can learn in a programming language is its data types. In this article, we will explore the various data types of Python language.

Python has data types such as numbers, lists, tuple, string, set, and dictionary. We will discuss them one by one below.

Numbers

The first data type in this language is the number that has integers, float and complex data types defined as "int", "float", and "complex" classes. What differs integers from the float is the presence of decimal points in float. For example, 7 is an integer, and 7.0 is a floating variable. A complex data type consists of two parts, a real part, and an imaginary part. For example, x+iy is a complex number where x is the real part and y is the imaginary part. We can use two functions to determine the class to which a number belongs.

1. type() - return the type of class of a particular variable

2. isinstance()- checks whether the given variable belongs to a class or not.

For example,

x = 3
print(type(x))
print(type(3.0))

c = 2 + 5j
print(isinstance(c, complex))

Output

<class 'int'>
<class 'float'>
True

The length of an integer data type can be of anything but the float data type has its accuracy up to 15 decimal places and after that it is inaccurate.

The number system such as binary(base 2), octal(base 8), and hexadecimal(base 16) can be represented using a set of prefixes such as

• Binary - '0b' or '0B'

• Octal - '0o' or '0O'

• Hexadecimal - '0x' or '0X'

The process of converting one data type into another is called type conversion. Automatic conversion happens for certain operations. For example, adding an integer and float will automatically result in a float, as it implicitly converts the integer to float.

>>> 1.0 + 5
6.0

We can also explicitly convert a variable of one data type into another by calling some built-in python functions such as int(), float(), complex().

>>> int(2.2)
2
>>> int(-7.8)
-7
>>> float(9)
9.0

Decimal

When we want the most accurate calculations like financial calculations, where precision is so important, we can use decimal instead of float. It can be used by importing the decimal module.

For example,

The second print statement involving the use of a decimal module results in a number with more accurate precision.

Fractions

If we want to use fractions where the numerator and denominator both are integers, we can import the fraction module.

For example,

import fractions

print(fractions.Fraction(0.5))
print(fractions.Fraction(5,6))

Output

1/2
5/6

Math and Random

The math() and random() modules in python offer a wide range of calculations in trigonometry, logarithms, statistics, etc.

For example,

import math
import random

print(math.pi)
print(math.factorial(4))
print(random.randrange(1, 8))

Output

3.141592653589793
24
5

Lists

The list is one of the most used data types in python that stores a sequence of elements in it. We will discuss briefly how to create a list, how to access elements from it, indexing, and more.

List creation

A list can be created by,

list_name= [ ]

The elements contained inside the square brackets are called the items of a list. The list can be either empty, contains items of the same type, different types, or even a list that contains its items. That is, a list can be

list_name=[ ]
list_name=[ 1,2,3,4,5]
list_name=[1, apple, 2, red, 5.5]
list_name=[1, 2, [red, green, yellow], 3, 4, 5]

Accessing an element

The elements contained inside a list have an index associated with them. The indices start from 0 and should be integers. A list of size 6 (6 elements) has an index starting from 0 to 5. The elements can be accessed using their respective indices.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
print(color_list)
print(color_list )

Output

g
e

print(color_list ) //This throws an "IndexError" as we have used an index that is beyond the index range of this list

Negative Indexing

In python, lists are indexed with a negative index starting from the last item in the list.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
print(color_list[-1])
print(color_list[-2])
print(color_list[-3])
print(color_list[-4])
print(color_list[-5])

Output

n
e
e
r
g

List Slicing

A range of elements from a list in python can be accessed by using the ":" operator (slicing operator).

For example,

color_list = ['g', 'r', 'e', 'e', 'n']

print(color_list[2:4])
print(color_list[:-3])
print(color_list[3:])
print(color_list[:])

Output

['e', 'e', 'n']
['g', 'r']
['e', 'n']
['g', 'r', 'e', 'e', 'n']

Lists elements can be added or modified (mutable) by using the " = " operator.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
color_list = b

print(color_list)

color_list[1:4]=['l', 'a', 'c', 'k']

print(color_list)

Output

['b', 'r', 'e', 'e', 'n']
['b', 'l', 'a', 'c', 'k']

We can add elements to the list by using append(),insert() and extend() methods.

For example,

num_list=[1,2,3,4,5]
num_list.append(6) //adds one element at the last
num_list.extend([7,8,9]) //adds a number of elements at the last
print(num_list)

Output

['1', '2', '3', '4', '5', '6', '7', '8', '9']

We can also concatenate two lists by using the '+' operator and multiply to a certain number of times using the '*' operator.

Deletion

Deletion can be performed by using the keywords del, or by using the functions such as remove(), pop(), or clear().

For example

mylist=['1', '2', '3', '4', 5', '6']

del mylist(2) //deletes the element at index 2
del mylist[1:3] //deletes the elements from index1 to 3
del mylist //deletes the entire list

mylist=['a', 'b, 'c', 'd', e', 'f']

mylist.remove('a') //removes the specified element 'a'
mylist.pop //removes the top most(last) element 'f'
mylist.clear() //removes the entire list

Some of the other methods that can be used with the lists are sort(), count(), reverse(), and copy().

Using the "in" keyword, we can check whether an element is present in a list or not and also can be used in list iterations.

Tuples

Tuples are similar to lists in python but they are immutable (cannot be modified).

They can be created by placing the elements inside the () and separated by commas.

For example,

mytuple = (1, 2, 3)

The elements inside the tuples can be of the same data type or different. The tuples can be created with or without a bracket.

Accessing the tuple elements is the same as the list elements. They can be accessed using indexing, negative indexing, and slicing.

For example,

mytuple = (1, 2, 3)

print(mytuple) //1
print(mytuple[-1]) //3
print(mytuple[1:2]) //2,3

Changing the elements in tuples can be done using the concatenation operator and deletion is done by using the keyword del.

Other methods can also be performed using the count(), index(), and a keyword for membership testing and iteration.

The major advantage of using tuples over lists is, iteration in tuples is easier as they are immutable.

Strings

A sequence of Unicode characters that are converted into binary characters for manipulation is called the strings in python. This process of converting a character into a binary number is called encoding and the reverse process is called decoding.

String creation

Strings are the characters that are enclosed within the quotes (either single or double).

For example,

string_name= 'My String'

print(string_name)

Output

My String

Accessing the characters inside a string is the same as accessing the list of tuples. They can be accessed by indexing, negative indexing, or slicing.

For example,

string_name= 'MyString'

print('string= ', string_name)
print('string = ', string_name)
print('string[-1] = ', string_name[-1])
print('string[1:5] = ', string_name[1:5])

Output

string= MyString
string= M
string[-1]= g
string[1:5]= yStri

Like tuples, strings are also immutable. We cannot modify or delete a particular character from a string, but we can delete the entire string by using the del keyword.

Some of the other operations performed in strings are concatenate (+),  multiply(*), enumerate(), len(), format(), lower(), upper(), join(), split(), find(),  and replace()

For example,

string_name= 'MyString'

>>>string_name.lower()
'mystring'

>>>string_name.upper()
'MYSTRING'

>>>My String.split()
['My', 'String']

>>>' '.join(['My', 'String'])
'My String'

>>>'My String'.replace('String','NewString')
'My NewString

>>>str1 = 'Hello'
>>>str2 ='How are you?'
>>>print('str1 + str2 = ', str1 + str2)
'Hello How are you?'

>>>print('str1 * 2 =', str1 * 2)
str1*2= HelloHello

Sets

A set is also a mutable data type that consists of unordered unique (immutable) elements in it.

They are used to perform operations like union, intersection, symmetric difference, and more.

Sets can be created by using {} brackets or by calling the set() function which is in-built. Sets can have any number of elements inside it and they can be of either the same or different data types.

For example,

my_set = {1, 2, 3}
print(my_set)

Output

{1, 2, 3}

Empty curly braces may be interpreted as a dictionary in python, so if we want to create an empty, we can do that by using the set() function.

Since sets are unordered, there is no index associated with the elements of sets. So we can add or delete an element from a set by using the functions such as add(), update(), discard() and remove().

For example,

set_name = {1, 3}
print(set_name) //1,3

print(set_name) //1,2,3

set_name.update([2, 3, 4])
print(set_name) //1,2,3,4

Similarly, we can also use the pop() or clear() method to do the deletion operations.

Sets are used to perform operations like union, intersection, symmetric difference, and more.

For example,

X = {1, 2, 3, 4, 5}
Y = {4, 5, 6, 7, 8}

print(X | Y)
print(X & Y)
print(X ^ Y)

Output

{1,2,3,4,5,4,5,6,7,8}
{4,5}
{1,2,3,4,5,6,7,8}

There are many other built-in functions available to operate with sets. They are all(), any(), enumerate(), len(), max(), min(), sorted(), sum() and more.

There is a function called frozenset() using which can create immutable sets, cannot be changed once assigned.

For example,

X = frozenset([1, 2, 3, 4])

Dictionary

Dictionary is a data type that contains an unordered sequence of items in it and each of its elements is associated with a key/value pair.

A dictionary in python can be created by,

dict_name = {1: 'red', 2: 'green'}

Elements of a dictionary can be accessed by keys associated with them, like the indexes in lists and tuples. Dictionary elements can be accessed using the get() method.

Example:

dict_name = {1: 'red', 2: 'green'}

print(dict_name.get(2))

Output

green

A new addition to a dictionary is done by using the assignment (=) operator. If you are trying to assign a value for an already existing key, the value will get updated. Deletion from a dictionary is done by using methods such as pop(), popitem(), clear(), and del keyword.

There are some built-in functions available to use with the dictionaries. They are  all(), any(), len(), cmp(), sorted().

In this article, we have learned about the different data types such as numbers, lists, tuples, strings, sets, and dictionaries along with their methods of addition, updation, how to access the elements from them, and more.

"We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs." Tag cloud 