Python: Data types

 

  Python: Data Types

We have seen that variables can hold values of different types called Data Types. Thus, we need different data types to store different Types of values in the variables. Sometimes, we also need to store answer in terms of only ‘yes’ or ‘no’, i.e., true or false. This type of data is known as Boolean data.

{tocify} $title= {Table of Contents}

Python has six basic data types which are as follows:

 1. Numeric

 2. String

 3. List

 4. Tuple

 5. Dictionary

 6. Boolean

1.  Numeric

Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers). Integers can themselves be positive or negative. Unlike many other programming languages, Python does not have any upper bound on the size of integers. The real numbers or fractional numbers are called floating point numbers in programming languages. Such floating point numbers contain a decimal and a fractional part.

Let us now look at an example that has an integer as well as a real number:

>>> num1=2      # integer number

>>>num2=2.5     # real number (float)

>>>num1

2                      # Output

>>>num2

2.5                    # Output

>>> 

NOTE:

In all the earlier versions of Python 3, slash (/) operator worked differently. When both numerator and denominator are integers, then the result will be an integer. The slash operator removes the fraction part.

Let us look at an example of the division operator in all the earlier versions of Python 3:

>>> 5/2

2             # Output

>>> 

The result becomes a floating number when either the numerator or the denominator is a floating number.

When both the numerator and the denominator are floating numbers, the result is again a floating number.

Let us look at an example of the division operator in all the earlier versions of Python 3:

>>> 5.0/2

2.5          # Output

>>> 

This operator has been modified in Python 3 and in all the versions after Python 3. The division operator provides accurate results even when both the numerator and the denominator are integers.

Here is an example of the division operator that is used in all the versions after Python 3:

>>> 5/2

2.5         # Output

>>> 

2.  String

Besides numbers, strings are another important data type. Single quotes or double quotes are used to represent strings. A string in Python can be a series or a sequence of alphabets, numerals and special characters. Similar to C, the first character of a string has an index 0.

There are many operations that can be performed on a string. There are several operators such as slice operator ([]) and [:]), concatenation operator (+), repetition operator (*), etc. Slicing is used to take out a subset of the string, concatenation is used to combine two or more than two strings and repetition is used to repeat the same string several times.

Here is an example of string data:

>>> sample_string =”Hello”   # store string value

>>> sample_string                  # display string value

‘Hello’                                       # Output

>>> sample_string + “World”          # use of + operator

‘HelloWorld’                                # Output

>>> sample_string * 3                        # use of * operator

‘HelloHelloHello’                         # Output

Python also provides slice operators ([] and [:]) to extract substring from the string. In Python, the indexing of the characters starts from 0; therefore, the index value of the first character is 0.

Syntax

>>> sample_string[start : end <:step>]        #step is optional

Example

>>>sample_string=”Hello”

>>>sample_string[1]        # display 1st index element.

‘e’                                            # Output

>>>sample_string[0:2]         # display 0 to 1st index elements

‘He’                                         # Output

Example

>>> sample_string = "HelloWorld"

>>> sample_string[1:8:2]     # display all the alternate charactors between index 1 to 8. i.e, 1,3,5,7

'elWr'            # Output

3.  List

List is the most used data type in Python. A list can contain the same type of items. Alternatively, a list can also contain different types of items. A list is an ordered and indexable sequence. To declare a list in Python, we need to separate the items using commas and enclose them within square brackets([]). The list is somewhat similar to the array in C language. However, an array can contain only the same type of items while a list can contain different types of items.

Similar to the string data type, the list also has plus (+), asterisk (*) and slicing [:] operators for concatenation, repetition and sub-list, respectively.

Let us look at an example of the List data type:

>>>first=[1,”two”,3.0,”four”]      # 1st list

>>>second=[“five”, 6]               # 2nd list

>>>first                  # display 1st list

[1, ‘two’, 3.0, ‘four’]      # Output

>>>first+second       # concatenate 1st and 2nd list

[1, ‘two’, 3.0, ‘four’, ‘five’, 6]    # Output

>>>second * 3         # repeat 2nd list

[‘five’, 6, ‘five’, 6, ‘five’, 6] # Output

>>>first[0:2]              # display sublist

[1, ‘two’]                         # Output

>>> 

4.  Tuple

Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of items separated by commas. However, tuples are enclosed within parentheses rather than within square brackets.

Let us look at an example of the tuple data type:

>>>third= (7, “eight”,9, 10.0)

>>>third

(7, ‘eight’, 9, 10.0)     # Output

Lists and tuples have the following differences:

● In lists, items are enclosed within square brackets [], whereas in tuples, items are enclosed within parentheses ().

● Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the items are stored, the tuple cannot be modified.

Note: - The items cannot be modified in a tuple but the same is not the case with a list.

Let us look at an example of list and tuple data type:

>>>first[0]=”one”

>>>third[0]=”seven”

Traceback (most recent call last):             # Output

File “<pyshell#15>”, line 1, in <module>

third[0]=”seven”

TypeError: ‘tuple’ object does not support item assignment

5.  Dictionary

It is the same as the hash table type. The order of elements in a dictionary is undefined. But, we can iterate over the following:

1. The keys

2. The values

3. The items (key-value pairs) in a dictionary

A Python dictionary is an unordered collection of key-value pairs. When we have the large amount of data, the dictionary data type is used. Keys and values can be of any type in a dictionary. Items in dictionary are enclosed in the curly-braces {} and separated by the comma (,). A colon (:) is used to separate key from value. A key inside the square bracket [] is used for accessing the dictionary items.

Example of dictionary:

>>> dict1 = {1:"first line", "second":2}   # declare dictionary

>>> dict1[3] = "third line"                         # add new item

>>> dict1                                                            # display dictionary

{1: 'first line', 'second': 2, 3: 'third line'}       #Output

>>> dict1.keys ()                                                # display dictionary keys

[1, 'second', 3]                                                    # Output

>>> dict1.values()                                              # display dictionary values

['first line', 2, 'third line']                                   # Output

6.  Boolean

In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to store the data in the form of ‘Yes’ or ‘No’. In terms of programming language, Yes is similar to True and No is similar to False.

This True and False data is known as Boolean Data and the data types which stores this Boolean data are known as Boolean Data Types.

Example

>>> a = True

>>> type(a)

<type ‘bool’>

>>> x = False

>>> type(x)

<type ‘bool’>

7.  Sets

The lists and dictionaries in Python are known as sequence or order collection of data. However, in Python we also have one data type which is an unordered collection of data known as Set. A Set does not contain any duplicate values or elements.

Union, Intersection, Difference and Symmetric Difference are some operations which are performed on sets.

Union: Union operation performed on two sets returns all the elements from both the sets. It is performed by using & operator.

Intersection: Intersection operation performed on two sets returns all the element which are common or in both the sets. It is performed by using | operator.

Difference: Difference operation performed on two sets set1 and set2 returns the elements which are present on set1 but not in set2. It is performed by using – operator.

Symmetric Difference: Symmetric Difference operation performed on two sets returns the element which are present in either set1 or set2 but not in both. It is performed by using ^ operator.

Example

 # Defining sets

>>> set1 = set([1, 2, 4, 1, 2, 8, 5, 4])

>>> set2 = set([1, 9, 3, 2, 5])

>>> print set1                                         #Printing set

set([8, 1, 2, 4, 5])                                      #Output

>>> print set2

set([1, 2, 3, 5, 9])                                         #Output

>>> intersection = set1 & set2                    #intersection of set1 and set2

>>> print intersection

set([1, 2, 5])                                                     #Output

>>> union = set1 | set2                                 # Union of set1 and set2Introduction to Python 13

>>> print union

set([1, 2, 3, 4, 5, 8, 9])                                              #Output

>>> difference = set1 - set2                   # Difference of set1 and set2

>>> print difference

set([8, 4]) #Output

>>> symm_diff = set1 ^ set2                     # Symmetric difference of set1 and

set2

>>> print symm_diff

set([3, 4, 8, 9])                                                      #Output

Type () Function

type() function in Python programming language is a built-in function which returns the datatype of any arbitrary object. The object is passed as an argument to the type() function. Type() function can take anything as an argument and returns its datatype such as integers, strings, dictionaries, lists, classes, modules, tuples, functions, etc.

Example

>>> x = 10

>>> type(x)

<type ‘int’>                    #Output

>>> type(‘hello’)

<type ‘str’>               #Output

>>> import os

>>> type (os)

<type ‘module’>          #Output

>>> tup = (1,2,3)

>>> type(tup)

<type ‘tuple’>                       #Output

>>> li = [1,2,3]

>>> type(li)

<type ‘list’>                                 #Output

>>> print union

set([1, 2, 3, 4, 5, 8, 9])              #Output

>>> difference = set1 - set2     # Difference of set1 and set2

>>> print difference

set([8, 4])                                     #Output

>>> symm_diff = set1 ^ set2       # Symmetric difference of set1 and

set2

>>> print symm_diff

set([3, 4, 8, 9])                                      #Output

Note Items separated by ‘comma’ is the signature of tuple not parenthesis.

 

Post a Comment (0)
Previous Post Next Post