Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. This post list the commonly used native data types supported in Python.
Numeric Data
Numeric data types supported in Python 3xx are
- int – int stands for integer. This Python Data Type holds signed integers.
- float– This holds floating point real values. An int can only store the number 3, but float can store 3.25 if you want.
- complex- This holds a complex number. A complex number looks like this: a+bj Here, a and b are the real parts of the number, and j is imaginary.
Example
# Integer data type a=-7 type(a) # Float data type a=-7.0 type(a) # Complex data type a=2+3j type(a) # Check if variable is of complex type print(isinstance(a,complex))
Use the isinstance() function to tell if variables belong to a particular class. It takes two parameters- the variable/value, and the class.
String
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ”’ or “””. Python does not have a char data type, unlike C++ or Java.
If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. If a string is to contain a single quote, delimit it with double quotes and vice versa. Other way is to use a backslash in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character.
city='Ahmedabad' city="Ahmedabad" # Span across multiple lines var = """This is a string that spans across several lines""" print(var) #Displaying part of a string print(city[0]) print(city[5:10]) var = "This string contains a single quote (') character." print(var) var = 'This string contains a single quote (\') character.' print(var) # Output This is a string that spans across several lines A abad This string contains a single quote (') character. This string contains a single quote (') character.
Boolean
Python 3 provides a Boolean data type. Objects of Boolean type may have one of two values, True or False.
Lists
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type. We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python. Lists are mutable, meaning, value of elements of a list can be altered. A list may have more than one dimension.
a = [1, 2.2, 'python'] a = [5,10,15,20,25,30,35,40] print(a[2]) print(a[0:3]) print(a[5:]) print(len(a)) # Reassigning elements of a list. a[2]='Wednesday' # Multiple dimensional list a=[[1,2,3],[4,5,6]] # Output 15 [5, 10, 15] [30, 35, 40] 8
Tuples
Tuple is an ordered sequence of items same as list.The only difference is that tuples are immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically. It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j) # Accessing print("t[1] = ", t[1]) print("t[0:3] = ", t[0:3]) # Generates error, Tuples are immutable t[0] = 10 # Output t[1] = program t[0:3] = (5, 'program', (1+3j))
Set
Set is an unordered collection of unique items. It is defined by values separated by comma inside braces { }. Items in a set are not ordered. Set have unique values. They eliminate duplicates. Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not work. Also, it is mutable. You can change its elements or add more. Use the add() and remove() methods to do so.
a = {5,2,3,1,4} # Printing set variable print("a = ", a) # Data type of variable a print(type(a)) # Adding new number a.add(10) # Output a = {1, 2, 3, 4, 5} <class 'set'>
Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type. You can reassign a value to a key.
d = {1:'value','key':2} print(type(d)) print("d[1] = ", d[1]); print("d['key'] = ", d['key']); # Reassigning elements d['key']=21 # Get a list of keys print(d.keys()) # Generates error print("d[2] = ", d[2]); # Output <class 'dict'> d[1] = value d['key'] = 2 dict_keys([1, 'key'])
Type Conversion
Since Python is dynamically-typed, you may want to convert a value into another type. Python supports a list of functions for the same.
- int() : It converts the value into an int.
# Float to int int(3.7) # Boolean to int int(True) # String number to int int("77") # String converting to int base 2 int('77', 10)
- float() : It converts the value into a float.
# Int to Float float(7) # Boolean to float float(True) # String number to float float("77") # Exponential number float("2.1e-2")
- str(): It converts the value into a string.
# Int to String str(7) # Float to String str(7.1) # Boolean to String str(True) # One can convert a list, a tuple, a set, or a dictionary into a string. str([1,2,3])
- bool(): It converts the value into a boolean.
print(bool(3)) print(bool(0)) print(bool(True)) print(bool(0.1)) # List into a Boolean. print(bool([1,2])) # Empty constructs. print(bool()) print(bool([])) print(bool({})) # None is a keyword irepresents an absence of value. print((bool(None))) # Output True False True True True False False False False
- set() : It converts the value into a set.
set([1,2,2,3]) set({1,2,2,3})
- list() : It converts the value into a list.
list("123") list({1,2,2,3}) list({"a":1,"b":2})
- tuple() :It converts the value into a tuple.
- dict() : It convert a tuple of order (key,value) into a dictionary.
- complex(real,imag) : It converts real numbers to complex(real,imag) number.
tuple({1,2,2,3}) tuple(list(set([1,2]))) # initializing integers a = 1 b = 2 # Initializing tuple tup = (('a', 1) ,('f', 2), ('g', 3)) # Integer to complex number c = complex(1,2) # Tuple to dictionary c = dict(tup)