Data Types
Data Types
The number data types are used to store the numeric values.
5 is an integer
5.42 is a floating-point number.
Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part.
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 5.42
print(num2, 'is of type', type(num2))
num3 = 8+2j
print(num3, 'is of type', type(num3))
Output
Number System Prefix
Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X
We have also used the type() function to know which class a certain
variable belongs to. Since,
5 is an integer value, type() returns int as the class of num1 i.e <class
'int'>
5.42 is a floating value, type() returns float as the class of num2 i.e
<class 'float'>
1 + 2j is a complex number, type() returns complex as the class of
num3 i.e <class 'complex'>
Number Systems:
The numbers we deal with every day are of the decimal (base 10)
number system.
print(0o15) # prints 13
num1 = int(2.3)
print(num1) # prints 2
num2 = int(-2.8)
print(num2) # prints -2
num3 = float(5)
print(num3) # prints 5.0
num4 = complex('3+5j')
print(num4) # prints (3 + 5j)
Here, when converting from float to integer, the number gets
truncated (decimal parts are removed).
import random
print(random.randrange(10, 20))
# Shuffle list1
random.shuffle(list1)
15
a
['d', 'b', 'c', 'e', 'a']
0.6716121217631744
To learn more about the random module, visit Python Random
Module.
Python Mathematics
Python offers the math module to carry out different mathematics like
trigonometry, logarithms, probability and statistics, etc. For example,
import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))
Output
3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720
Python Keywords and Identifiers
Python Keywords
Keywords are predefined, reserved words used in Python
programming that have special meanings to the compiler.
We cannot use a keyword as a variable name, function name, or any
other identifier. They are used to define the syntax and structure of the
Python language.
All the keywords except True, False and None are in lowercase and
they must be written as they are. The list of all the keywords is given
below.
Python Keywords List
score @core
return_value return
name1 1name
In computer programming, data types specify the type of data that can
be stored inside a variable
int, float,
Numeric holds numeric values
complex
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
Output
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
In the above example, we have created three variables
named num1, num2 and num3 with values 5, 5.0,
and 1+2j respectively.
We have also used the type() function to know which class a certain
variable belongs to.
Since,
• 5 is an integer value, type() returns int as the class
of num1 i.e <class 'int'>
• 2.0 is a floating value, type() returns float as the class
of num2 i.e <class 'float'>
• 1 + 2j is a complex number, type() returns complex as the class
of num3 i.e <class 'complex'>
Create a List:
print(ages)
A list can
store elements of different types (integer, float, string, etc.),
store duplicate elements
# empty list
list3 = []
In Python, lists are ordered and each item in a list is associated with a
number. The number is known as a list index.
The index of the first element is 0, second element is 1 and so on. For
example,
print(languages[0]) # Python
print(languages[2]) # C++
Here, we can see each list item is associated with the index number.
And we have used the index number to access the items.
Remember: The list index always starts with 0. Hence, the first
element of a list is present at index 0, not 1.
Note: If the specified index does not exist in a list, Python throws the
IndexError exception.
Slicing of a List:
my_list = ['p','r','o','g','r','a','m','i','z']
Output
1. Using append()
The append() method adds an item at the end of the list. For example,
numbers.append(32)
Here, append() adds 32 at the end of the array.
2. Using extend()
We use the extend() method to add all the items of an iterable (list,
tuple, string, dictionary, etc.) to the end of the list. For example,
numbers = [1, 3, 5]
even_numbers = [4, 6, 8]
Output
3. Using insert():
numbers.insert(1, 20)
Python lists are mutable. Meaning lists are changeable. And we can
change items of a list by assigning new values using the = operator.
For example,
languages = ['Python', 'Swift', 'C++']
languages[2] = 'C'
Remove an Item From a List
In Python we can use the del statement to remove one or more items
from a list. For example,
2. Using remove():
We can also use the remove() method to delete a list item. For
example,
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
We use the in keyword to check if an item exists in the list or not. For
example,
List Length:
We use the len() function to find the size of a list. For example,
Output
The list pop() method removes the item at the specified index. The
method also returns the removed item.
list.pop(index)
pop() parameters
# Updated List
print('Updated List:', languages)
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
Example
prime_numbers = [2, 3, 5, 7, 9, 11]
list.clear()
clear() Parameters
The clear() method doesn't take any parameters.
print('List:', list)
Output
List: []
The count() method returns the number of times the specified element
appears in the list.
Example
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
# Output: Count of 2: 3
list.count(element)
count() Parameters
# print count
print('The count of i is:', count)
# print count
print('The count of p is:', count)
Output
# print count
print("The count of ('a', 'b') is:", count)
# print count
print("The count of [3, 4] is:", count)
Output
Example
prime_numbers = [11, 3, 7, 5, 2]
print(prime_numbers)
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's built-in sorted() function for
the same purpose.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it
has two optional parameters:
If you want a function to return the sorted list rather than change the
original list, use sorted().
# print vowels
print('Sorted list:', vowels)
Output
Sorted list: ['a', 'e', 'i', 'o', 'u']
list.sort(reverse=True)
Alternatively for sorted(), you can use the following code.
sorted(list, reverse=True)
Example 2: Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# print vowels
print('Sorted list (in Descending):', vowels)
Output
If you want your own implementation for sorting, the sort() method
also accepts a key function as an optional parameter.
Based on the results of the key function, you can sort the given list.
list.sort(key=len)
Alternatively for sorted:
sorted(list, key=len)
Here, len is Python's in-built function to count the length of an
element.
The list is sorted based on the length of each element, from lowest
count to highest.
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# print list
print('Sorted list:', random)
Output
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]
Let's take another example. Suppose we have a list of information
about the employees of an office where each element is a dictionary.
def get_age(employee):
return employee.get('age')
def get_salary(employee):
return employee.get('salary')
Output
For the second case, age (int) is returned and is sorted in ascending
order.
For the third case, the function returns the salary (int), and is sorted in
the descending order using reverse = True.
It is a good practice to use the lambda function when the function can
be summarized in one line. So, we can also write the above program
as:
Example
# mixed list
prime_numbers = [2, 3, 5]
# copying a list
numbers = prime_numbers.copy()
copy() Syntax
new_list = list.copy()
copy() Parameters
The copy() method returns a new list. It doesn't modify the original
list.
# copying a list
new_list = my_list.copy()
Output
old_list = [1, 2, 3]
new_list = old_list
Howerver, there is one problem with copying lists in this way. If you
modify new_list, old_list is also modified. It is because the new list is
referencing or pointing to the same old_list object.
old_list = [1, 2, 3]
Output
Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']
However, if you need the original list unchanged when the new list is
modified, you can use the copy() method.
# mixed list
list = ['cat', 0, 6.7]
Method Description
extend() add all the items of an iterable to the end of the list
Creating a Tuple
A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas. The parentheses are optional,
however, it is a good practice to use them.
A tuple can have any number of items and they may be of different
types (integer, float, list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
In the above example, we have created different types of tuples and
stored different data items inside them.
my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4
var1 = ("hello")
print(type(var1)) # <class 'str'>
# Parentheses is optional
var3 = "hello",
print(type(var3)) # <class 'tuple'>
Here,
("hello") is a string so type() returns str as class of var1 i.e. <class
'str'>
("hello",) and "hello", both are tuples so type() returns tuple as class
of var1 i.e. <class 'tuple'>
Access Python Tuple Elements
1.Indexing:
We can use the index operator [] to access an item in a tuple, where
the index starts from 0.
The index of -1 refers to the last item, -2 to the second last item and
so on. For example,
3. Slicing:
We can access a range of items in a tuple by using the slicing operator
colon :.
In Python ,methods that add items or remove items are not available
with tuple. Only the following two methods are available.
print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
Run Code
Here,
Here,
Since tuples are quite similar to lists, both of them are used in similar
situations.
name = "Python"
print(name)
Python
I love Python.
In the above example, we have created string-type variables: name
and message with values "Python" and "I love Python" respectively.
Here, we have used double quotes to represent strings but we can use
single quotes too.
Access String Characters in Python:
Indexing: One way is to treat strings as a list and use index values.
For example,
greet = 'hello'
Output
We can also create a multiline string in Python. For this, we use triple
double quotes """ or triple single quotes '''. For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Output
There are many operations that can be performed with strings which
makes it one of the most used data types in Python.
False
True
In the above example,
str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.
# using + operator
result = greet + name
print(result)
In Python, we use the len() method to find the length of a string. For
example,
greet = 'Hello'
# Output: 5
Methods Description
Suppose we need to include both double quote and single quote inside
a string,
print(example)
# Output: He said, "What's there?"
Here is a list of all the escape sequences supported by Python.
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
name = 'Cathy'
country = 'UK'
Output
Cathy is from UK
Here, f'{name} is from {country}' is an f-string.
Python Sets
Output
Student ID: {112, 114, 115, 116, 118}
Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}
In the above example, we have created different types of sets by
placing all the elements inside the curly braces {}.
Note: When you run this code, you might get output in a different
order. This is because the set has no particular order.
Output
Data type of empty_set: <class 'set'>
Data type of empty_dictionary <class 'dict'>
Here,
• empty_set - an empty set created using set()
• empty_dictionary - an empty dictionary created using {}
Finally we have used the type() function to know which
class empty_set and empty_dictionary belong to.
print('Initial Set:',numbers)
Output
Initial Set: {34, 12, 21, 54}
Updated Set: {32, 34, 12, 21, 54}
In the above example, we have created a set named numbers. Notice
the line,
numbers.add(32)
Here, add() adds 32 to our set.
companies.update(tech_companies)
print(companies)
# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}
print('Initial Set:',languages)
Output
Initial Set: {'Python', 'Swift', 'Java'}
Set after remove(): {'Python', 'Swift'}
Here, we have used the discard() method to remove 'Java' from
the languages set.
Built-in Functions with Set
Built-in functions
like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc.
are commonly used with sets to perform different tasks.
Function Description
Returns True if all elements of the set are true (or if the set is
all()
empty).
Returns True if any element of the set is true. If the set is emp
any()
returns False.
Output
Set: {8, 2, 4, 6}
Total Elements: 4
Here, we have used the len() method to find the number of elements
present in a Set.
Set Union in
Python
We use the | operator or the union() method to perform the set union
operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Union using |: {0, 1, 2, 3, 4, 5}
Union using union(): {0, 1, 2, 3, 4, 5}
Note: A|B and union() is equivalent to A ⋃ B set operation.
Set Intersection
The intersection of two sets A and B include the common elements
between set A and B.
Set Intersection
in Python
In Python, we use the & operator or the intersection() method to
perform the set intersection operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}
Note: A&B and intersection() is equivalent to A ⋂ B set operation.
Difference between Two Sets
The difference between two sets A and B include elements of
set A that are not present on set B.
Set Difference in
Python
We use the - operator or the difference() method to perform the
difference between two sets. For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
Output
Difference using &: {3, 5}
Difference using difference(): {3, 5}
Note: A - B and A.difference(B) is equivalent to A - B set operation.
Set Symmetric Difference
The symmetric difference between two sets A and B includes all
elements of A and B without the common elements.
Set Symmetric
Difference in Python
In Python, we use the ^ operator or
the symmetric_difference() method to perform symmetric difference
between two sets. For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Check if two sets are equal
We can use the == operator to check whether two sets are equal or
not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
Output
Set A and Set B are equal
In the above example, A and B have the same elements, so the
condition
if A == B
evaluates to True. Hence, the statement print('Set A and Set B are
equal') inside the if is executed.
Other Python Set Methods
Method Description
Python Dictionary
Create a Dictionary
We create dictionaries by placing key:value pairs inside curly
brackets {}, separated by commas. For example,
# creating a dictionary
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England':
'London'}
The country_capitals dictionary has three elements (key-value pairs).
Note: Dictionary keys must be immutable, such as tuples, strings,
integers, etc. We cannot use mutable (changeable) objects such as lists
as keys.
# Valid dictionary
my_dict = {
1: "Hello",
(1, 2): "Hello Hi",
3: [1, 2, 3]
}
print(my_dict)
# Invalid dictionary
# Error: using a list as a key is not allowed
my_dict = {
1: "Hello",
[1, 2]: "Hello Hi",
}
print(my_dict)
print(country_capitals["England"]) # London
Note: We can also use the get() method to access dictionary items.
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England':
'London'}
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'Germany':
'Berlin'}
Note: We can also use the update method() to add or change
dictionary items.
print(country_capitals)
Output
{'Italy': 'Naples'}
Note: We can also use the pop method() to remove an item from the
dictionary.
If we need to remove all items from the dictionary at once, we can use
the clear() method.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
country_capitals.clear()
print(country_capitals) # {}