DATA TYPES IN PYTHON

Since everything is object in python programming, So every values in python has a data type.The various data types in python are:

  1. Numbers.
  2. List.
  3. Tuples.
  4. Strings
  5. Set
  6. Dictionary

1.Numbers

In python numbers are categorized as :

  • Int  (ex: 3, 4, 5 , …)
  • Float (ex: 3.0, 4.0, 5.0 , …)
  • Complex (ex:1+2j,  2+3j , 2+5j, …)

We can use type( ) function to  check which class a variable or value belongs to.

2.LIST

List is ordered sequence of items. All the items in the list do not need to be of same type. List is one of the most widely used data type in python and it is very flexible.

Declaration of list is straight forward. In list declaration items are separated by commas and are enclosed within bracket [ ].

l

List are mutable ,meaning, value of the element of the list can be changed.

We can use slicing operator [ ] to extract an item or  range of items from a  list. Index starts from 0 in python

i/p>>>list[0:3]

o/p>>> [1,2,3]

3.TUPLE

Tuple is an ordered sequence of item same as list. The only difference is that tuples are immutable(tuple once created can not be modified) and tuples are dfined within parentheses ( ) and are separated with commas.

>>> t = (4,6,”this is a tuple”,2+3j)

Tuples are usually faster than list as it cannot change dynamically.

We can use slicing operator in tuple but we can not change the value of tupple

 4.Strings

String is a sequence of Unicode characters. We can use singe quotes (‘ ’) or double quotes (“  ”) to represent a string. Everything written within quotes are string.

Multi-line string can be denoted using triple quotes ‘ ‘ ‘ or  “ “ “.

>>> s= ‘this is a string’

>>> s=’’’this is a multiline string

Strings are immutable. Like list and tuple slicing [ ] operator can be used in string.

 5.SET

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }.

We can perform set operations like union ,intersection on two set

Sets have unique values so they eliminate duplicates.

> a = {1, 2, 2, 2, 3, 3, 3}

>> a

{1, 2, 3}

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not work.

>> a = {3, 4, 5}

> a[1]

Traceback (most recent call last): File “<string>”, line 301, in runcode  File “<interactive input>”, line 1, in <module>TypeError: ‘set’ object does not support indexing

 6.Dictionary

Dictionary is unordered collection of key-value pairs. In python dictionary are defined within braces { } with each items being a pair in the form of key: value. Key and value can be of any type.

> d = {‘key’: 6, 1:’value’, }

>>> type(d)<class ‘dict’>

To retrieve the respective value we use key

>>>d[1]

>>>value

Leave a comment