Python Data Types
In this article, we will see “Python Data Types”. It will help you in implementing different data types in Python.
Data types in Python
Each and every value in Python has a datatype and these data types determine what operations can be performed on that particular data.
In Python, everything is an object. Data types are classes and variables are objects (instance of the classes)
Python has various built-in data types. Let’s see the most important data types of Python here.
Python Numbers (Numeric)
Python has three categories of numbers such as integer, float, and complex number.
type() function is used to find which class a variable or a value belongs to.
isinstance() function is used to find if an object belongs to a particular class.
Integers – int – Positive or negative whole numbers (without a fractional part). There is no limit for integers. The only limit is due to memory availability. A floating-point number is accurate up to 15 decimal places. Example: 1 is an integer.
Floating-point numbers – float – Any real number with a floating-point representation (with a fractional part). Example: 1.0 is a float-point number.
Complex numbers – complex classes in Python – x+yj is represented as a real and imaginary component. x and y are floats and j is -1(square root of -1 called an imaginary number).
a = 1 print(a, "is of type", type(a)) b = 1.0 print(b, "is of type", type(b)) c = 0123456 print(c, "is of type", type(c)) d = 2+3j print(d, "is complex number?", isinstance(2+3j,complex))
Output:
imaginary number)
1 is of type <class 'int'>
1.0 is of type <class 'float'> 0123456 is of type <class 'int'>
(2+3j) is complex number? True
Python List
Python list is an ordered sequence of data items.
All the data items in a list not necessarily of the same type. Data items in the list are separated by commas and enclosed within brackets [].
a = [1, 1.0, 'python']
Index in python starts from 0. Let’s use the slicing operator [] to extract a data item or a range of data items from a list.
a = [5,10,15,20,25,30,35,40] # a[1] = 10 print("a[1] = ", a[1]) # a[0:4] = [5, 10, 15, 20] print("a[0:4] = ", a[0:4]) # a[6:] = [35, 40] print("a[6:] = ", a[6:])
Output
a[1] = 10 a[0:4] = [5, 10, 15, 20] a[6:] = [35, 40]
Lists are mutable whereas Strings are not mutable. Learn Strings in Python here.
In the lists, we can change the value of elements.
a = [2, 4, 6] a[2] = 8 print(a)
Output
[2, 4, 8]
Python Tuple
Python tuple is an ordered sequence of data items. It is the same as List but tuples in python are immutable. Once you create a tuple you cannot modify it.
All the data items in a tuple not necessarily of the same type. Data items in the tuple are separated by commas and enclosed within parentheses ().
Tuples are used to write-protect data.
Tuples are faster than lists because tuples once created cannot be changed dynamically.
a = (2,'python', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
a = (2,'python', 1+3j) # a[1] = 'python' print("a[1] = ", a[1]) # a[0:3] = (2, 'python', (1+3j)) print("a[0:3] = ", a[0:3]) # Generates error because tuples are immutable a[0] = 10
Output
a[1] = python a[0:3] = (2, 'python', (1+3j)) Traceback (most recent call last): File "test.py", line 11, in <module> a[0] = 10 TypeError: 'tuple' object does not support item assignment
Python Strings
In Python, Strings are a collection of one or more characters enclosed by either single quotation marks or double quotation marks or triple quotation marks. Python treats both single and double quotes as same. Multiline Strings can be denoted using triple quotes, ”’ or “””.
# Python Program for creation of String # Creating a string with single quotes a = 'stm' print(a) # Creating a string with double quotes b = "stm" # Creating a string with triple quotes print(b) c = '''Learning Python Strings at Software Testing Material''' print(c)
Output
stm
stm
Learning Python Strings
at Software Testing Material
Let’s apply a slicing operator [] to the strings as what we did for List & Tuple.
Note: Strings are immutable.
a = 'Learn Python' # a[4] = 'n' print("a[4] = ", a[4]) # a[6:12] = 'python' print("a[6:12] = ", a[6:12]) # Generates error # Strings are immutable in Python a[5] ='d'
Output
a[4] = n a[6:12] = Python Traceback (most recent call last): File "<string>", line 11, in <module> TypeError: 'str' object does not support item assignment
Python Set
We have seen an ordered sequences like List & Tuple. Now we will see the unordered collection of objects.
Set is an unordered collection of objects which are unique.
All the data items in a Set not necessarily of the same type. Data items in the Set are separated by commas and enclosed within braces {}.
a = {5,4,3,1,2} # printing set variable
print("a = ", a) # data type of variable a
print(type(a))
Output
a = {1, 2, 3, 4, 5} <class 'set'>
We can perform mathematical set operations like union, intersection on two sets, etc.,
The set has unique values and eliminates duplicates.
a = {1,2,2,3,3,4,4} print(a)
Output
{1, 2, 3, 4}
Note: As mentioned earlier, sets are the unordered collection. So the slicking operator [] doesn’t work with Set in Python.
Python Dictionary
Dictionary object is an unordered collection fo data in a key:value pairs. A collection of such pairs is enclosed in curly brackets {} with each item being a pair in the key:value form.
key and value can be of any data type.
We use Dictionary in python when we have a huge amount of data.
Dictionary in python is used to retrieve the data but we must know the key to retrieve the value.
>>> a = {1:'value','key':2}
>>> type(a)
<class 'dict'>
To retrieve the value we use a key.
a = {1:'value','key':2}
print(type(a)) print("a[1] = ", a[1]); print("a['key'] = ", a['key']); # Generates error
print("a[2] = ", a[2]);
Output
<class 'dict'>
a[1] = value
a['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
Conversion between data types
We can use type conversion functions like int(), float(), str(), etc., to convert between different data types.
Conversion from float to int:
>>> int(1.5)
1
>>> int(-1.5)
-1
Conversion from int to float:
>>> float(1)
1.0
Convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({4, 5,6})
(4, 5, 6)
>>> list('python')
['p', 'y', 't', 'h', 'o', 'n']
Convert to a dictionary: Each element must be a pair
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,25),(4,50)])
{3: 25, 4: 50}
Also Read:
- Python Strings
- Python Multiline Strings
- Python Join() Method with Examples
- How to Convert Python List to String (4 Ways)
- Python float() Function Explained with Examples
- Python Interview Questions