Datatypes In Python Programming

aimtocode

DataType Definition

Data types are means to identify the type of data and associated operations for handling it. In python, we need not to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type accordingly.

Data types represent a kind of value which determines what operations can be performed on that given data.

Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Standard data types

Python has five standard data types −


1) Number DataType

Number data types store numeric values. Number objects are created when you assign a value to them. For example

 
 var1 =1
 var2 =10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

 del var1[,var2[,var3[	,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −

 del var
 del var_a,var_b

Python supports four different numerical types −

  • 1) int (signed integers like 10, 2, 29, etc.)
  • 2) long (long integers, they can also be represented in octal and hexadecimal like 908090800L, -0x1929292L, etc.)
  • 3) float (floating point real values 1.9, 9.902, 15.2, etc.)
  • 4) complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

Different number format example

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j


2) String DataType

Strings in Python are identified as a contiguous set of characters represented in the quotation marks.

Python allows for either pairs of single(' ') or double quotes(" ").

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. For example –



This will produce the following result –

 Python Programming
 P
 g
 tho
 thon Programming
 Python ProgrammingPython Programming
 Python Programming Course


List DataType

Lists are the most versatile of Python's compound data types.

A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.,/

One difference between them is that all the items belonging to a list can be of different data type in python.

The values stored in a 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 −



Output:

 ['Hai', 123, 1.75, 'Prayag', 100.25]
 Hai
 100.25
 [123, 1.75]
 [1.75, 'Prayag', 100.25]
 [251, 'Verma', 251, 'Verma']
 ['Hai', 123, 1.75, 'Prayag', 100.25, 251, 'Verma']


Tuple

A tuple is a sequence of immutable Python objects.

Tuples are sequences, just like lists.

The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses (), whereas lists uses square brackets [].

Creating Tuples

Similar to List, Tuple is a sequence of values. The values can be any type, and they are indexed by integers.

The important difference is that tuples are immutable. Syntactically, a tuple is a comma-separated list of values:

 >>>message= 'h','a','i'
 >>> type(message)
 <type 'tuple'>

Although it is not necessary, it is common to enclose tuples in parentheses:

 >>> message= ('h','a','i')
 >>> type(message)
 <type 'tuple'>

To create a tuple with a single element, you have to include a final comma:

 >>> t1 = 'a',
 >>> type(t1)
 <class 'tuple'>

A value in parentheses is not a tuple:

 >>> t2 = ('a')
 >>> type(t2)
 <class 'str'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:

 >>> t = tuple()
 >>> t ()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence:

 >>> course=tuple('python')
 >>> course
 ('p', 'y', 't', 'h', 'o', 'n')

Because tuple is the name of a built-in function, you should avoid using it as a variable name.

Most list operators also work on tuples. The square bracket operator indexes an element:

 >>> course = ('p', 'y', 't', 'h', 'o', 'n')
 >>> cource[0] 'p'

Slice Operator

And the slice operator selects a range of elements.

 >>> course[3:5] ('h', 'o')

But if you try to modify one of the elements of the tuple, you get an error:

 >>> course[0]='P'

Output:

 TypeError: 'tuple' object does not support item assignment

Because tuples are immutable, you can‘t modify the elements. But you can replace one tuple with another:

 >>> course=('P',)+course[1:]
 >>> course
 ('P', 'y', 't', 'h', 'o', 'n')

This statement makes a new tuple and then makes course refer to it. The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered, even if they are really big.

Tuple Assignment

It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:

 >>> temp = a
 >>> a = b
 >>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

 >>> a, b = b, a	
 

The left side is a tuple of variables; the right side is a tuple of expressions.

Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

 >>> a, b = 1, 2, 3

 ValueError: too many values to unpack

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:

>>> email='support@aimtocode.com'
>>> username,domain=email.split('@')

The return value from split is a list with two elements; the first element is assigned to username, the second to domain.

 >>> username 'support'
 >>> domain 'aimtocode.com'

Tuples as return Values

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.

For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:

 >>> t = divmod(7, 3)
 >>> t (2, 1)

Here is an example of a function that returns a tuple:

 def min_max(t):
 return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values.

 >>> quot 2
 >>> rem 1


DICTIONARIES DataType

Dictionaries are one of Python‘s best features; they are the building blocks of many efficient and elegant algorithms.

A Dictionary is a Mapping: A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.

In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key ―maps to‖ a value. As an example, we‘ll build a dictionary that maps from English to Tamil words, so the keys and the values are all strings.

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.

Creates Dictionary



Output:

 1st name is Prayag
 2nd name is Ritesh
 {1: 'Prayag', 2: 'Sujeet', 3: 'Rahul', 4: 'Ritesh'}
 dict_keys([1, 2, 3, 4])
 dict_values(['Prayag', 'Sujeet', 'Rahul', 'Ritesh'])
aimtocode