Learn everything about Analytics

Home » Data Types in Python

Data Types in Python

This article was published as a part of the Data Science Blogathon

Introduction

Python is a general-purpose interpreted, interactive, object-oriented high-level programming language that supports the development and implementation of a wide range of applications. It is a user-friendly language that is easy to learn and use. Python is being used in many diverse fields to build applications like system administration, GUI programs, database applications, scripting, etc.

Python offers a vast variety of data types that help in the implementation of various applications. In this article, we are going to study the basic data types of python along with their built-in functions and their use.

 

Table of contents-

  • Numeric data type
  • Strings
  • List
  • Dictionary

 

Numeric Data types-

There are 4 types of numeric data types in python: –

1) Int – It stores the integers values that can be positive or negative and do not contain any decimal point.

E.g – num1=10, num2 = 15

2) Float – These are floating-point real numbers that stores the decimal values. It consists of integer and fraction parts.

E.g – fnum = 25.4, fnum1=67.8

3) Complex – These are complex numbers specified as a real part and an imaginary part. They are stored in the form of a + bj where a is the real part and j represents the imaginary part.

E.g – num3= 2 + 3j, numcom = 5 – 7j

>>> num1=10
>>> print(num1)
10
>>> type(num1)
<class 'int'>
>>> fnum=26.5
>>> print(fnum)
26.5
>>> type(fnum)
<class 'float'>
>>> num3=2 + 6j
>>> print(num3)
(2+6j)
>>> type(num3)
<class 'complex'>

Strings

A string is a sequence of characters enclosed in single quotes double quotes or triple quotes. The character present in a string can be any digit, letter, special symbols, or white spaces. String in python is an immutable data type that is once a value is assigned to the variable it cannot be changed later.

E.g – str1=“Apple12”

Str2= ‘hello’

Str3 = ”Hey, welcome to Analytics Vidya “

Accessing values in a string:-

Each character of a string can be expressed with the help of a technique called indexing. In indexing, each character has an index value represented by either a positive or negative integer starting from 0.

Syntax:- stringname[index]

E.g –

Str1=”Python
#accessing second character 
Str1[1]
#accessing first four characters
Str1[0:4]  # it will print the value from index 0 to 3
str1="Python"
>>> str1[1]
'y'
>>> str1[0:4]
'Pyth'
   Positive indexing     0    1      2      3      4      5
  String    P     y      t       h      o      n
  Negative indexing    -6    -5     -4     -3     -2     -1

 

String operations-

1) Concatenation – Python allows us to join two different strings using the concatenation operator ‘+’ .

Syntax:– str1 + str2

Eg-

>>> str1="Analytic"
>>> str2="Vidya"
>>> str3=str1 +str2
>>> print(str3)
AnalyticVidya

2) Repetitions – Python allows us to repeat a given string with the help of ‘ * ‘ operator.

Syntax:– stringname * integervalue

Eg-

>>> str2 = "python"
>>> str2 * 3
'pythonpythonpython'

3) Membership – The Membership operator helps to check whether a given character is present in the string or not with the help of two operators in and not in. In and not in operator returns the boolean value True or False.

Syntax:– character in/not in stringname

Eg:-

>>> str1="python"
>>> "p" in  str1
True
>>> "f" in str1
False

Built-in function in strings –

1) Len() – It is used to calculate the length of the given string.

Syntax:– len(stringname)

Eg:-

>>> str1="Python"
>>> len(str1)
6

2) isupper() – This function is used to check whether all the letters in a string are in the upper case or not. If all the characters are in upper case then it returns True otherwise it returns False.

Syntax:– stringname.isupper()

Eg:-

>>>str1= " Hello Everyone"
>>> str1.isupper()
False
>>> str2="HELLO"
>>> str2.isupper()
True

3) islower() – This function is used to check whether all the letters in a string are in lowercase or not. If all the characters are in lower case then it returns True otherwise it returns False.

Syntax::– stringname.islower()

e.g:-

>>> s="hello"
>>> s.islower()
True
>>> s1="hey Folks!"
>>> s1.islower()
False

4) upper() – It is used to convert all the characters of a string in uppercase.

Syntax:– stringname.upper()

Eg-

>>>str1= " Hello Everyone"
>>> str1.upper()
' HELLO EVERYONE'

5) lower() – It is used to convert all the characters of a string in lowercase.

Syntax:– stringname.lower ()

Eg-

>>> str2="HELLO"
>>> str2.lower()
'hello'

List

A list is a collection of elements that belongs to different data types like int, float, string, list, etc. all the elements of the list are enclosed in square brackets and are separated by the comma with each other. The list is a mutable data type that is we can change the elements of the list once it is created.

Eg:-

List1=[123,567,89] #list of numbers

List2=[“hello”,”how”,”are”] #list of strings

List3= [“hey”,1223,”hello”] #list of mixed data type.

Accessing elements of the list:-

Elements of the list are accessed in the same as that of string that is with the help of positive and negative indexing. Slicing is also used to access the list elements in which more than a single element is accessed at a time.

List1=[“apple”,123,”mango”,[2,3,4,]]

   Positive index    0        1         2        3
      List   “apple”     123    “mango”    [2,3,4]
    Negative index     -4     -3       -2     -1

Eg-

>>> list1=['apple',123,"mango",[2,3,4,]]
>>> list1[0]
'apple'
>>> list1[3]
[2, 3, 4]
>>> list1[1:3]
[123, 'mango']

Operations in list

1) Concatenation – Two lists are concatenated with the help of “+” operator.

Syntax:- list1 + list2
>>> list1=["apple","mango",123,345]
>>> list2 = ["grapes"]
>>> list1 + list2
['apple', 'mango', 123, 345, 'grapes']

2) Repititions – With the help of the ‘ * ‘ operator list can be repeated n number of times.

Syntax:- list1* number
>>> list1=["apple","mango",123,345]
>>> list1*2
['apple', 'mango', 123, 345, 'apple', 'mango', 123, 345]

3) Membership – ‘ in ‘and ‘ not in ‘ are two membership operators that are used to check whether the given element is present in the list or not and return a Boolean value True or False.

Syntax:– element in/not in in list1
>>> list1=["apple","mango",123,345]
>>> 'apple' in list1
True
>>> 'apple' not in list1
False

Built-in functions in the list

1) append() – This function is used to add a single element at the end of the list. The single element that is added can be of any data type like integer, list, string, etc.

Syntax :- listname.append(element)
>>> list1=["apple","mango","grapes",123,345]
>>> list1.append("orange")
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange']
>>> list1.append([12,34,55])
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange', [12, 34, 55]]

2) insert() – insert() function is also used to add element in this list but with the help of insert we can add the element at a particular index in the list. If the index is not present then it will add the element at the end of the list.

Syntax :- listname.insert (index,element)
>>> list2=["apple","mango","grapes",123,345]
>>> list2.insert(0,234)
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345]
>>> list2.insert(6,"papapa")
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345, 'papapa']

3) count() – count function is used to count the number of time an element occurs in the list.

Syntax:– listname.count(element)
>>> list3=[12,45,12,67,78,90]
>>> list3.count(12)
2
>>> list3.count(11)
0

4) reverse() – reverse function is used to reverse the order of elements in the list.

Syntax:– listname.reverse()
>>> list3=[12,45,12,67,78,90]
>>> list3.reverse()
>>> list3
[90, 78, 67, 12, 45, 12]

5) sort() – sort function is used to arrange the elements of the list in ascending order. The function list must contain all the elements in the same data type that is either integers or strings.

Syntax:– listname.sort()
list4=["grapes","banana","apple","mango"]
>>> list4.sort()
>>> list4
['apple', 'banana', 'grapes', 'mango']
>>>list5=[12,45,12,67,78,90]
>>>list5.sort()
[12,12,45,67,78,90]

Dictionary

Dictionary is a special data type that is a mapping between a set of keys and a set of values. Dictionary represents a key-value pair enclosed in curly brackets and each element is separated by a comma. Key-value pairs are separated by the colon. The elements of the dictionaries are unordered and the key is unique for each value in the dictionary. The elements of the dictionary are mutable that is its elements can be changed once it is created.

Syntax:-

Dictionaryname={key:value}

Eg:-

Dict1={“comp”: “computer” , “sci” : “science”}

Dict2={“123”:”computer”,456 : “maths”}

Accessing elements of the dictionary:-

The elements of the dictionary are accessed with the help of the keys. Each key serves as an index and maps the value in the dictionary.

Syntax:- dictionaryname[key]
>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comp"]
'computer'
>>> dict1["sci"]
'science'

New elements are added in the dictionary with the help of a new key.

>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comm"]="commerce"
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce'}

Built-in functions in the dictionary-

1) items() – items() function returns a list of tuples of key-value pair of the dictionary.

Syntax:- dictionaryname.items()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.items()
dict_items([('comp', 'computer'), ('sci', 'science'), ('comm', 'commerce')])

2) keys() – This function returns the list of keys in the dictionary.

Syntax:- dictionaryname.keys()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.keys()
dict_keys(['comp', 'sci', 'comm'])

3) values() – It returns the list of values in the dictionary.

Syntax:- dictionaryname.values()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.values()
dict_values(['computer', 'science', 'commerce'])

4) len() – length function is used to count the total number of elements in the dictionary.

Syntax:- len(dictionaryname)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> len(dict1)
3

5) update() –it is used to append the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary.

Syntax:- dictionary1.update(dictionary2)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict2={"acc":"accounts","bst":"business studies"}
>>> dict1.update(dict2)
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce', 'acc': 'accounts', 'bst': 'business studies'}

Conclusion

From the article, we can see that Python has many data types that can help in the classification or categorization of data items. Data types represent the kind of value any variable can store and what all operations can be performed on them. Also, some of the built-in data types of python are mutable that can be changed later while some of them are immutable that can not be changed later. These data types also have many built-in functions that make our tasks much easier and faster.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

You can also read this article on our Mobile APP Get it on Google Play