Python Data Types
·
Data Type is a particular type of data item which is defined by the values.
·
Python is a dynamically typed language so do not
define the type of the variable when declaring it.
·
Python interpreter automatically reads
variables according to data. Ex. Integer, float, string, etc..
·
type() function
returns the type of the variable in python.
·
isinstance() function
is used to check a particular class of an object.
Classification of datatypes
Divided into two categories, 1. Immutable data
types and 2. Mutable data types.
Immutable Data types in Python
1. Numeric
2. String
3. Tuple
Mutable Data types in Python
1. List
2. Dictionary
3. Set
Standard scalar data types
Python provides various standard scalar data
types which are:-
- Numbers
- Sequence Type
- Boolean
- Set
- Dictionary
1.
Numbers
Number stores numeric values such as integer,
float, and complex values.
Python supports three types of numeric data.
- Int
- Integer value store any
length and without decimal values ex. 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an
integer.
- Float
- Float is store
floating-point numbers (decimal or fractional value) ex. 1.9, 9.902, 15.2,
etc.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts.
Numbers with real and imaginary parts are known as complex numbers.
Ex. 2.14j, 2.0 + 2.3j, etc.
In Python, we can print decimal equivalent of binary, octal and hexadecimal numbers
using the prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number
For example;
a = 5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
# integer equivalent of binary number 101
num = 0b101
print(num)
# integer equivalent of Octal number 32
num2 = 0o32
print(num2)
# integer equivalent of Hexadecimal number FF
num3 = 0xFF
print(num3)
output:- 5
26
255
--------------------------------------------------------------------------------------------------------------------
2. Sequence Type
A. String
· The string is a bit of text (sequence of characters) denoted in the quotation marks.
· Python can use single, double, or triple quotes to define a string.
· String handling defines built-in functions and operators to perform various operations in the string.
· A string is an array of characters, so use the indexes to access the characters.
· Just like arrays, the indexes start from 0 to the length-1.
· Index Error display if try to access the character which is not in the range.
Example:- create strings in Python
str = 'HELLO'
print(str)
str2 = "SJKPGM"
print(str2)
# multi-line string
str3 = """Welcome to
sjkpgm.in"""
print(str3)
str4 = '''This is a tech
blog'''
print(str4)
Output:
HELLO
SJKPGM
Welcome to
Sjkpgm.in
This is a tech
blog
example:- TypeError .
str = "abcde"
# displaying whole string
print(str)
# displaying first character of string
print(str[0])
# displaying the third character of the string
print(str[2])
# displaying the last character of the string
print(str[-1])
# displaying the second last char of the string
print(str[-2])
Output:
abcde
a
c
e
d
--------------------------------------------------------------------------------------------------------------------
B. List
· Python Lists are similar to arrays in C.
· list can contain data of different types(heterogenous / compound which means use different data types such as integer, float, and string items in the same list).
· The data of the list are separated by a comma (,) and enclosed within square brackets [ ].
· For accessing data from the list use slice [:] operators.
· slice() function / operators returns a slice object/ part of any type(string, bytes,tuple, list or range).(Syntax: slice(start, stop, step)).
· The concatenation operator (+) and repetition operator (*) works with the list in the same as the strings.
· Negative Index to access the list items from the end Ex. an index of -1 would access the last element of the list, -2 second last, -3 third last, and so on.
Example:-
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
Output:
[1, 'hi', 'Python', 2]
#Printing the list1
print (list1)
Output:
[1, 'hi', 'Python', 2]
# List slicing
print (list1[3:])
Output:
[2]
# List slicing
print (list1[0:2])
Output:
[1, 'hi',]
# List Concatenation using + operator
print (list1 + list1)
output:-
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
# List repetation using * operator
print (list1 * 3)
Output:
[ 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Accessing the items of a list
Syntax:
list_name[index]
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
# prints 300
print(numbers[5])
# prints 22
print(numbers[1])
Output:
11
300
22
Example:-
Negative Index to access the list items from the end
# a list of strings
my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
print(my_list[-1])
Output:
bye
# prints "world"
print(my_list[-3])
Output:
world
# prints "hello"
print(my_list[-4])
Output:
Hello
----------------------------------------------------------------------------------------------------------------
C. Tuple
· A tuple is similar to the list and contains heterogeneous data items.
· tuples contain the collection of the items of different data types, separated with a comma (,) and enclosed in parentheses ().
· A tuple can have string and list as data items.
· A tuple is a read-only data structure, can't modify the size and value of the items of
a tuple.
· Tuple with only a single element must put a comma after the element, otherwise
Python will not treat it as a tuple it will treat as an int variable.
Ex. my_data = (99,).
· Accessing tuple elements by the indexes.
· Negative indexes in tuples is Similar to list and strings. to access the tuple
elements from the end. ex. -1 to access the last element, -2 to access second last,
and so on.
· Example:-
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
Output:
<class 'tuple'>
#Printing the tuple
print (tup)
Output:
('hi', 'Python', 2)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
('Python', 2)
('hi',)
example:-
# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data)
# tuple of int, float, string
my_data2 = (1, 2.8, "Hello World")
print(my_data2)
# tuple of string and list
my_data3 = ("Book", [1, 2, 3])
print(my_data3)
# tuples inside another tuple
# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))
print(my_data4)
Output:
('hi', 'hello', 'bye')
(1, 2.8, 'Hello World')
('Book', [1, 2, 3])
((2, 3, 4), (1, 2, 'hi'))
Empty tuple:
# empty tuple
my_data = ()
Example:- Accessing tuple elements using positive indexes Indexes start with 0 that
is why we use 0 to access the first element of the tuple, 1 to access the second
element, and so on.
# tuple of strings
my_data = ("hi", "hello", "bye")
# displaying all elements
print(my_data)
# accessing first element
# prints "hi"
print(my_data[0])
# accessing third element
# prints "bye"
print(my_data[2])
Output:
('hi', 'hello', 'bye')
hi
bye
Negative indexes in tuples
my_data = (1, 2, "Kevin", 8.9)
# accessing last element
# prints 8.9
print(my_data[-1])
# prints 2
print(my_data[-3])
Output:
8.9
2
-----------------------------------------------------------------------------------------------------------------
D. Dictionary
- Dictionary is an unordered set of a key-value pair of items.
- It is like an associative array or a hash table where each key stores a specific value.
- Key can hold any primitive data type, whereas value is a random Python object. Dictionary is a mutable data type in Python.
- The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
- The left side of the colon (:) is the key and the right side of the: is the value.
example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
Keys must be unique in the dictionary, duplicate values are allowed.
A dictionary is said to be empty if it has no key-value pairs. An empty dictionary is
denoted like this: {}.
The keys of the dictionary must be of immutable data types such as String, numbers,
or tuples.
# Printing dictionary
print (d)
# Accessing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
example:-
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
Access dictionary values using keys in the square.
example.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
print("Student Age is:", mydict['StuAge'])
print("Student City is:", mydict['StuCity'])
Output:
============================================================ Boolean
Boolean type provides two built-in values,
True and False.
These values are used to determine the given
statement true or false.
It is denoted by the class bool.
True can be represented by any non-zero value or 'T' whereas false can be
represented by the 0 or 'F'. example:-
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
=================================================================
Set
· Set is the unordered and unindexed collection of items (data type).
· Unordered means random order.
· Unindexed means, cannot access the elements of a set using the indexes
like List and tuples.
· It is iterated able, mutable (can modify after creation), and has unique
elements.
· the order of the elements is undefined; it may return the changed
sequence of the element.
· The set is created by using a built-in function set (), or a sequence of
elements is passed in the curly braces and separated by the comma.
· It can contain various types of values.
Example:-
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
Output:
{3, 'Python', 'James', 2}
# Adding element to the set
set2.add(10)
print(set2)
Output: {'Python', 'James', 3, 2, 10}
#Removing element from the set
set2.remove(2)
print(set2)
Output:
{'Python', 'James', 3, 10}
Example:
Set = {5,1,2.6,"python"}
print(Set)
Output: {‘python', 1, 5, 2.6}
Example:
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
print('A U B =', A| B)
Output:
A U B = {‘c', ‘a’, 2, ‘d'}
A = {100, 7, 8}
B = {200, 4, 7}
print(A & B)
Output: {7}
For example –
myset = [1, 2, 3, 4, "hello"]
Example
# Set Example
myset = {"hi", 2, "bye", "Hello World"}
print(myset)
Output:
============================================================
0 Comments