Python Data Types
Although we don’t have to declare type for python variables, a value does have a type. This information is vital to the interpreter. Python supports the following Python data types.
a. Numbers
There are four numeric Python data types.
1. int– int stands for integer. This Python Data Type holds signed integers. We can use the type() function to find which class it belongs to.
- >>> a=-7
- >>> type(a)
<class ‘int’>
An integer can be of any length, with the only limitation being the available memory.
- >>> a=9999999999999999999999999999999
- >>> type(a)
<class ‘int’>
2. float– This Python Data Type holds floating point real values. An int can only store the number 3, but float can store 3.25 if you want.
- >>> a=3.0
- >>> type(a)
- <class 'float'>
3. long – This Python Data Types holds a long integer of unlimited length. But this construct does not exist in Python 3.x.
4. complex- This Python Data Types 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.
- >>> a=2+3j
- >>> type(a)
<class ‘complex’>
Use the isinstance() function to tell if python variables belong to a particular class. It takes two parameters- the variable/value, and the class.
>>> print(isinstance(a,complex))
True
True
b. Strings
A string is a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can delimit a string using single quotes or double quotes.
- >>> city='Ahmedabad'
- >>> city
‘Ahmedabad’
- >>> city="Ahmedabad"
- >>> city
‘Ahmedabad’
1. Spanning a string across lines – To span a string across multiple lines, you can use triple quotes.
- >>> var="""If
- only"""
- >>> var
‘If\n\tonly’
>>> print(var)
If
Only
- >>> """If
- only"""
‘If\n\tonly’
As you can see, the quotes preserved the formatting (\n is the escape sequence for newline, \t is for tab).
2. Displaying part of a string– You can display a character from a string using its index in the string. Remember, indexing starts with 0.
- >>> lesson='disappointment'
- >>> lesson[0]
‘d’
You can also display a burst of characters in a string using the slicing operator [].
>>> lesson[5:10]
‘point’
‘point’
This prints the characters from 5 to 9.
3. String Formatters– String formatters allow us to print characters and values at once. You can use the % operator.
- >>> x=10;
- >>> printer=”Dell”
- >>> print(“I just printed %s pages to the printer %s” % (x, printer))
Or you can use the format method.
- >>> print(“I just printed {0} pages to the printer {1}”.format(x, printer))
- >>> print(“I just printed {x} pages to the printer {printer}”.format(x=7, printer=Dell))
A third option is to use f-strings.
>>>print(f”I just printed {x} pages to the printer {printer}”)
4. String Concatenation– You can concatenate(join) strings.
- >>> a='10'
- >>> print(a+a)
1010
However, you cannot concatenate values of different types.
>>> print('10'+10)
Traceback (most recent call last):
File “<pyshell#89>”, line 1, in <module>;
print(’10’+10)
TypeError: must be str, not int
Traceback (most recent call last):
File “<pyshell#89>”, line 1, in <module>;
print(’10’+10)
TypeError: must be str, not int
c. Lists
A list is a collection of values. Remember, it may contain different types of values. To define a list, you must put values separated with commas in square brackets. You don’t need to declare a type for a list either.
- >>> days=['Monday','Tuesday',3,4,5,6,7]
- >>> days
[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]
1. Slicing a list – You can slice a list the way you’d slice a string- with the slicing operator.
>>> days[1:3]
[‘Tuesday’, 3]
[‘Tuesday’, 3]
Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays.
2. Length of a list– Python supports an inbuilt function to calculate the length of a list.
>>> len(days)
7
7
3. Reassigning elements of a list– A list is mutable. This means that you can reassign elements later on.
- >>> days[2]='Wednesday'
- >>> days
[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]
4. Multidimensional lists– A list may have more than one dimension. We will look further into this in the tutorial on Python Lists.
- >>> a=[[1,2,3],[4,5,6]]
- >>> a
[[1, 2, 3], [4, 5, 6]]
d. Tuples
A tuple is like a list. You declare it using parentheses instead.
- >>>subjects=('Physics','Chemistry','Maths')
- >>> subjects
(‘Physics’, ‘Chemistry’, ‘Maths’)
1. Accessing and Slicing a Tuple– You access a tuple the same way as you’d access a list. The same goes for slicing it.
>>> subjects[1]
‘Chemistry’
>>> subjects[0:2]
(‘Physics’, ‘Chemistry’)
‘Chemistry’
>>> subjects[0:2]
(‘Physics’, ‘Chemistry’)
2. A tuple is immutable– However, it is immutable. Once declared, you can’t change its size or elements.
>>> subjects[2]='Biology'
Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
TypeError: ‘tuple’ object does not support item assignment
>>> subjects[3]='Computer Science'<strong></strong>
Traceback (most recent call last):
File “<pyshell#108>”, line 1, in <module>
subjects[3]=’Computer Science’
TypeError: ‘tuple’ object does not support item assignment
Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
TypeError: ‘tuple’ object does not support item assignment
>>> subjects[3]='Computer Science'<strong></strong>
Traceback (most recent call last):
File “<pyshell#108>”, line 1, in <module>
subjects[3]=’Computer Science’
TypeError: ‘tuple’ object does not support item assignment
e. Dictionaries
A dictionary holds key-value pairs. Declare it in curly braces, with pairs separated by commas. Separate keys and values by a colon(:).
- >>> person={'city':'Ahmedabad','age':7}
- >>> person
{‘city’: ‘Ahmedabad’, ‘age’: 7}
The type() function works with dictionaries too.
>>> type(person)
<class ‘dict’>
<class ‘dict’>
1. Accessing a value– To access a value, you mention the key in square brackets.
- >>> person['city']
‘Ahmedabad’
2. Reassigning elements– You can reassign a value to a key.
- >>> person['age']=21
- >>> person['age']
21
3. List of keys– Use the keys() function to get a list of keys in the dictionary.
- >>> person.keys()
dict_keys([‘city’, ‘age’])
f. bool
A Boolean value can be True or False.
- >>> a=2>1
- >>> type(a)
g. Sets
A set can have a list of values. Define it using curly braces.
- >>> a={1,2,3}
- >>> a
{1, 2, 3}
It returns only one instance of any value present more than once.
- >>> a={1,2,2,3}
- >>> a
{1, 2, 3}
However, a set is unordered, so it doesn’t support indexing.
>>> a[2]
Traceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
a[2]
TypeError: ‘set’ object does not support indexing
Traceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
a[2]
TypeError: ‘set’ object does not support indexing
Also, it is mutable. You can change its elements or add more. Use the add() and remove() methods to do so.
- >>> a={1,2,3,4}
- >>> a
{1, 2, 3, 4}
- >>> a.remove(4)
- >>> a
{1, 2, 3}
- >>> a.add(4)
- >>> a
{1, 2, 3, 4}
If any queries regarding this topic then comments below..
Thank you :)
Read : Python Global, Local and Nonlocal variables
Read : Python Anonymous/Lambda Function
Comments
Post a Comment