0% found this document useful (0 votes)
27 views

Data Types

Python supports integers, floating-point numbers and complex numbers defined as int, float, and complex classes. It can determine the class of a variable using type() and perform numeric operations and conversions. It also supports random number generation and mathematical functions through its random and math modules.

Uploaded by

223111
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Data Types

Python supports integers, floating-point numbers and complex numbers defined as int, float, and complex classes. It can determine the class of a variable using type() and perform numeric operations and conversions. It also supports random number generation and mathematical functions through its random and math modules.

Uploaded by

223111
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Python Numbers, Type Conversion and Mathematics:

The number data types are used to store the numeric values.

Python supports integers, floating-point numbers and complex


numbers. They are defined as int, float, and complex classes in
Python.

int - holds signed integers of non-limited length.


float - holds floating decimal points and it's accurate up to 15 decimal
places.
complex - holds complex numbers.
Python Numeric Data Type

Integers and floating points are separated by the presence or absence


of a decimal point. For instance,

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.

We can use the type() function to know which class a variable or a


value belongs to.

Let's see an example,

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

5 is of type <class 'int'>


5.42 is of type <class 'float'>
(8+2j) is of type <class 'complex'>
In the above example, we have created three variables named num1,
num2 and num3 with values 5, 5.42, and 8+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'>
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.

But computer programmers need to work with binary (base 2),


hexadecimal (base 16) and octal (base 8) number systems.

In Python, we can represent these numbers by appropriately placing a


prefix before that number. The following table lists these prefixes.

print(0b1101011) # prints 107


print(0xFB + 0b10) # prints 253

print(0o15) # prints 13

Type Conversion in Python:

In programming, type conversion is the process of converting one


type of number into another.

Operations like addition, subtraction convert integers to float


implicitly (automatically), if one of the operands is float. For
example,

print(1 + 2.0) # prints 3.0


Run Code
Here, we can see above that 1 (integer) is converted into 1.0 (float) for
addition and the result is also a floating point number.

Explicit Type Conversion


We can also use built-in functions like int(), float() and complex() to
convert between types explicitly. These functions can even convert
from strings.

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).

Similarly when converting from integer to float, .0 is postfixed to the


number.

Python Random Module:

Python offers the random module to generate random numbers or to


pick a random item from an iterator.

First we need to import the random module. For example,

import random

print(random.randrange(10, 20))

list1 = ['a', 'b', 'c', 'd', 'e']

# get random item from list1


print(random.choice(list1))

# Shuffle list1
random.shuffle(list1)

# Print the shuffled list1


print(list1)

# Print random element


print(random.random())
Run Code
Output

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

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


Looking at all the keywords at once and trying to figure out what they
mean might be overwhelming.
Python Identifiers
Identifiers are the name given to variables, classes, methods, etc. For
example,
language = 'Python'
Here, language is a variable (an identifier) which holds the
value 'Python'.
We cannot use keywords as variable names as they are reserved
names that are built-in to Python. For example,
continue = 'Python'

Rules for Naming an Identifier


• Identifiers cannot be a keyword.
• Identifiers are case-sensitive.
• It can have a sequence of letters and digits. However, it must
begin with a letter or _. The first letter of an identifier cannot be
a digit.
• It's a convention to start an identifier with a letter rather _.
• Whitespaces are not allowed.
• We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python


Valid Identifiers Invalid Identifiers

score @core

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string


Things to Remember
Python is a case-sensitive language. This
means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a
valid name, writing count = 10 would make more sense, and it would
be easier to figure out what it represents when you look at your code
after a long gap.
Multiple words can be separated using an underscore,
like this_is_a_long_variable
Python Data Types:

In computer programming, data types specify the type of data that can
be stored inside a variable

Python Data Types


Data
Classes Description
Types

int, float,
Numeric holds numeric values
complex

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

holds data in key-value pair


Mapping dict
form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items

Since everything is an object in Python programming, data types are


actually classes and variables are instances(object) of these classes.
Python Numeric Data type

In Python, numeric data type is used to hold numeric values.


Integers, floating-point numbers and complex numbers fall
under Python numbers category. They are defined
as int, float and complex classes in Python.

• int - holds signed integers of non-limited length.


• float - holds floating decimal points and it's accurate up
to 15 decimal places.
• complex - holds complex numbers.

We can use the type() function to know which class a variable or a


value belongs to.
Let's see an example,
num1 = 5
print(num1, 'is of type', type(num1))

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:

We create a list by placing elements inside [], separated by commas.


For example,

ages = [19, 26, 23]

print(ages)

# Output: [19, 26, 23]

Here, we have created a list named ages with 3 integer items.

A list can
store elements of different types (integer, float, string, etc.),
store duplicate elements

# list with elements of different data types

list1 = [1, "Hello", 3.4]

# list with duplicate elements

list1 = [1, "Hello", 3.4, "Hello", 1]

# empty list

list3 = []

Note: We can also create a list using the list() constructor.


Access List Elements

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,

languages = ["Python", "Swift", "C++"]

# access item at index 0

print(languages[0]) # Python

# access item at index 2

print(languages[2]) # C++

In the above example, we have created a list named languages.

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.

Negative Indexing in Python

Python allows negative indexing for its sequences. The index of -1


refers to the last item, -2 to the second last item and so on.

Let's see an example,

languages = ["Python", "Swift", "C++"]


# access item at index 0
print(languages[-1]) # C++

# access item at index 2


print(languages[-3]) # Python

Note: If the specified index does not exist in a list, Python throws the
IndexError exception.

Slicing of a List:

In Python, it is possible to access a portion of a list using the slicing


operator :. For example,

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# items from index 2 to index 4


print(my_list[2:5])

# items from index 5 to end


print(my_list[5:])

# items beginning to end


print(my_list[:])

Output

['o', 'g', 'r']


['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Here,

my_list[2:5] returns a list with items from index 2 to index 4.


my_list[5:] returns a list with items from index 5 to the end.
my_list[:] returns all list items
Note: When we slice lists, the start index is inclusive, but the end
index is exclusive.

Add Elements to a List:

Lists are mutable (changeable). Meaning we can add and remove


elements from a list.

Python list provides different methods to add items to a list.

1. Using append()

The append() method adds an item at the end of the list. For example,

numbers = [21, 34, 54, 12]

print("Before Append:", numbers)

# using append method


numbers.append(32)

print("After Append:", numbers)


Output

Before Append: [21, 34, 54, 12]


After Append: [21, 34, 54, 12, 32]
In the above example, we have created a list named numbers. Notice
the line

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]

# add elements of even_numbers to the numbers list


numbers.extend(even_numbers)

print("List after append:", numbers)

Output

List after append: [1, 3, 5, 4, 6, 8]


Here, numbers.extend(even_numbers) adds all the elements of
even_numbers to the numbers list.

3. Using insert():

We use the insert() method to add an element at the specified index.

numbers = [10, 30, 40]

# insert an element at index 1 (second position)

numbers.insert(1, 20)

print(numbers) # [10, 20, 30, 40]

Change List Items:

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++']

# changing the third item to 'C'


languages[2] = 'C'

print(languages) # ['Python', 'Swift', 'C']


Run Code
Here, initially the value at index 3 is 'C++'. We then changed the value
to 'C' using

languages[2] = 'C'
Remove an Item From a List

1. Using del Statement:

In Python we can use the del statement to remove one or more items
from a list. For example,

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item


del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item


del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']

# delete the first two items


del languages[0 : 2] # ['C', 'Java', 'Rust']
print(languages)

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']

# remove 'Python' from the list


languages.remove('Python')

print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

Here, languages.remove('Python') removes 'Python' from the


languages list.

Check if an Element Exists in a List:

We use the in keyword to check if an item exists in the list or not. For
example,

languages = ['Python', 'Swift', 'C++']

print('C' in languages) # False


print('Python' in languages) # True
Here,

'C' is not present in languages, 'C' in languages evaluates to False.


'Python' is present in languages, 'Python' in languages evaluates to
True.

List Length:

We use the len() function to find the size of a list. For example,

languages = ['Python', 'Swift', 'C++']

print("List: ", languages)


print("Total Elements: ", len(languages)) #3

Output

List: ['Python', 'Swift', 'C++']


Total Elements: 3

Python List pop()

The list pop() method removes the item at the specified index. The
method also returns the removed item.

Syntax of List pop()


The syntax of the pop() method is:

list.pop(index)

pop() parameters

The pop() method takes a single argument (index).


The argument passed to the method is optional. If not passed, the
default index -1 is passed as an argument (index of the last item).
If the index passed to the method is not in range, it throws IndexError:
pop index out of range exception.

# programming languages list


languages = ['Python', 'Java', 'C++', 'French', 'C']

# remove and return the 4th item


return_value = languages.pop(3)

print('Return Value:', return_value)

# Updated List
print('Updated List:', languages)
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']

Python List clear()

The clear() method removes all items from the list.

Example
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements


prime_numbers.clear()

# Updated prime_numbers List


print('List after clear():', prime_numbers)

# Output: List after clear(): []

Syntax of List clear()


The syntax of clear() method is:

list.clear()

clear() Parameters
The clear() method doesn't take any parameters.

Return Value from clear()


The clear() method only empties the given list. It doesn't return any
value.
Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


list.clear()

print('List:', list)

Output

List: []

Python List count()

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]

# check the count of 2


count = numbers.count(2)

print('Count of 2:', count)

# Output: Count of 2: 3

Syntax of List count()

The syntax of the count() method is:

list.count(element)
count() Parameters

The count() method takes a single argument:

element - the element to be counted

Return value from count()

The count() method returns the number of times element appears in


the list.

Example 1: Use of count()


# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'


count = vowels.count('i')

# print count
print('The count of i is:', count)

# count element 'p'


count = vowels.count('p')

# print count
print('The count of p is:', count)

Output

The count of i is: 2


The count of p is: 0
Example 2: Count Tuple and List Elements Inside List
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
# count element ('a', 'b')
count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)

# count element [3, 4]


count = random.count([3, 4])

# print count
print("The count of [3, 4] is:", count)

Output

The count of ('a', 'b') is: 2


The count of [3, 4] is: 1

Python List sort():

The sort() method sorts the items of a list in ascending or descending


order.

Example
prime_numbers = [11, 3, 7, 5, 2]

# sorting the list in ascending order


prime_numbers.sort()

print(prime_numbers)

# Output: [2, 3, 5, 7, 11]


sort() Syntax
The syntax of the sort() method is:

list.sort(key=..., reverse=...)
Alternatively, you can also use Python's built-in sorted() function for
the same purpose.

sorted(list, key=..., reverse=...)


Note: The simplest difference between sort() and sorted() is: sort()
changes the list directly and doesn't return any value, while sorted()
doesn't change the list and returns the sorted list.

sort() Parameters
By default, sort() doesn't require any extra parameters. However, it
has two optional parameters:

reverse - If True, the sorted list is reversed (or sorted in Descending


order)
key - function that serves as a key for the sort comparison

sort() Return Value


The sort() method doesn't return any value. Rather, it changes the
original list.

If you want a function to return the sorted list rather than change the
original list, use sorted().

Example 1: Sort a given list


# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort()

# print vowels
print('Sorted list:', vowels)
Output
Sorted list: ['a', 'e', 'i', 'o', 'u']

Sort in Descending order


The sort() method accepts a reverse parameter as an optional
argument.

Setting reverse = True sorts the list in the descending order.

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']

# sort the vowels


vowels.sort(reverse=True)

# print vowels
print('Sorted list (in Descending):', vowels)
Output

Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']


Sort with custom function using key

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.

We know that a tuple is sorted using its first parameter by default.


Let's look at how to customize the sort() method to sort using the
second element.

Example 3: Sort the list using key


# take second element for sort
def takeSecond(elem):
return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key


random.sort(key=takeSecond)

# 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.

We can sort the list in the following way:

# sorting using custom key


employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# custom functions to get employee info


def get_name(employee):
return employee.get('Name')

def get_age(employee):
return employee.get('age')

def get_salary(employee):
return employee.get('salary')

# sort by name (Ascending order)


employees.sort(key=get_name)
print(employees, end='\n\n')

# sort by Age (Ascending order)


employees.sort(key=get_age)
print(employees, end='\n\n')

# sort by salary (Descending order)


employees.sort(key=get_salary, reverse=True)
print(employees, end='\n\n')

Output

[{'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, {'Name': 'John


Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Mikhail Tal', 'age': 40,
'salary': 15000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}]
[{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Alan
Turing', 'age': 25, 'salary': 10000}, {'Name': 'Sharon Lin', 'age': 30,
'salary': 8000}, {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}]

[{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Alan


Turing', 'age': 25, 'salary': 10000}, {'Name': 'Sharon Lin', 'age': 30,
'salary': 8000}, {'Name': 'John Hopkins', 'age': 18, 'salary': 1000}]
Here, for the first case, our custom function returns the name of each
employee. Since the name is a string, Python by default sorts it using
the alphabetical order.

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:

# sorting using custom key


employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# sort by name (Ascending order)


employees.sort(key=lambda x: x.get('Name'))
print(employees, end='\n\n')

# sort by Age (Ascending order)


employees.sort(key=lambda x: x.get('age'))
print(employees, end='\n\n')
# sort by salary (Descending order)
employees.sort(key=lambda x: x.get('salary'), reverse=True)
print(employees, end='\n\n')

Python List copy()


The copy() method returns a shallow copy of the list.

Example
# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()

print('Copied List:', numbers)

# Output: Copied List: [2, 3, 5]

copy() Syntax

The syntax of the copy() method is:

new_list = list.copy()

copy() Parameters

The copy() method doesn't take any parameters.

copy() Return Value

The copy() method returns a new list. It doesn't modify the original
list.

Example: Copying a List


# mixed list
my_list = ['cat', 0, 6.7]

# copying a list
new_list = my_list.copy()

print('Copied List:', new_list)

Output

Copied List: ['cat', 0, 6.7]


If you modify the new_list in the above example, my_list will not be
modified.

List copy using =

We can also use the = operator to copy a list. For example,

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]

# copy list using =


new_list = old_list

# add an element to list


new_list.append('a')

print('New List:', new_list)


print('Old List:', old_list)

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.

Example: Copy List Using Slicing Syntax

# shallow copy using the slicing syntax

# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing


new_list = list[:]

# Adding an element to the new list


new_list.append('dog')

# Printing new and old list


print('Old List:', list)
print('New List:', new_list)
Output

Old List: ['cat', 0, 6.7]


New List: ['cat', 0, 6.7, 'dog']
List Methods:
Python has many useful list methods that makes it really easy to work
with lists.

Method Description

append() add an item to the end of the list

extend() add all the items of an iterable to the end of the list

insert() inserts an item at the specified index

remove() removes item present at the given index

pop() returns and removes item present at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list


Python Tuple:

A tuple in Python is similar to a list. The difference between the two


is that we cannot change the elements of a tuple once it is assigned
whereas we can change the elements of a 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.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
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.

As mentioned earlier, we can also create tuples without using


parentheses:

my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4

Create a Python Tuple With one Element

In Python, creating a tuple with one element is a bit tricky. Having


one element within parentheses is not enough.

We will need a trailing comma to indicate that it is a tuple,

var1 = ("Hello") # string


var2 = ("Hello",) # tuple
We can use the type() function to know which class a variable or a
value belongs to.

var1 = ("hello")
print(type(var1)) # <class 'str'>

# Creating a tuple having one element


var2 = ("hello",)
print(type(var2)) # <class 'tuple'>

# 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

Like a list, each element of a tuple is represented by index numbers


(0, 1, ...) where the first element is at index 0.

We use the index number to access tuple elements. For example,

1.Indexing:
We can use the index operator [] to access an item in a tuple, where
the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to


access an index outside of the tuple index range( 6,7,... in this
example) will raise an IndexError.

The index must be an integer, so we cannot use float or other types.


This will result in TypeError.

Likewise, nested tuples are accessed using nested indexing, as shown


in the example below.

# accessing tuple elements using indexing


letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0]) # prints "p"


print(letters[5]) # prints "a"
Run Code
In the above example,

letters[0] - accesses the first element


letters[5] - accesses the sixth element
2. Negative Indexing:

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and
so on. For example,

# accessing tuple elements using negative indexing


letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(letters[-1]) # prints 'z'


print(letters[-3]) # prints 'm'
Run Code
In the above example,

letters[-1] - accesses last element


letters[-3] - accesses third last element

3. Slicing:
We can access a range of items in a tuple by using the slicing operator
colon :.

# accessing tuple elements using slicing


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index


print(my_tuple[1:4]) # prints ('r', 'o', 'g')

# elements beginning to 2nd


print(my_tuple[:-7]) # prints ('p', 'r')

# elements 8th to end


print(my_tuple[7:]) # prints ('i', 'z')

# elements beginning to end


print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Output

('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Here,

my_tuple[1:4] returns a tuple with elements from index 1 to index 3.


my_tuple[:-7] returns a tuple with elements from beginning to index
2.
my_tuple[7:] returns a tuple with elements from index 7 to the end.
my_tuple[:] returns all tuple items.
Note: When we slice lists, the start index is inclusive but the end
index is exclusive.

Python Tuple Methods:

In Python ,methods that add items or remove items are not available
with tuple. Only the following two methods are available.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
Run Code
Here,

my_tuple.count('p') - counts total number of 'p' in my_tuple


my_tuple.index('l') - returns the first occurrence of 'l' in my_tuple

Check if an Item Exists in the Python Tuple:

We use the in keyword to check if an item exists in the tuple or not.


For example,
languages = ('Python', 'Swift', 'C++')

print('C' in languages) # False


print('Python' in languages) # True

Here,

'C' is not present in languages, 'C' in languages evaluates to False.


'Python' is present in languages, 'Python' in languages evaluates to
True.

Advantages of Tuple over List in Python:

Since tuples are quite similar to lists, both of them are used in similar
situations.

However, there are certain advantages of implementing a tuple over a


list:

We generally use tuples for heterogeneous (different) data types and


lists for homogeneous (similar) data types.
Since tuples are immutable, iterating through a tuple is faster than
with a list. So there is a slight performance boost.
Tuples that contain immutable elements can be used as a key for a
dictionary. With lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will
guarantee that it remains write-protected.
Python Strings:

In computer programming, a string is a sequence of characters. For


example, "hello" is a string containing a sequence of characters 'h', 'e',
'l', 'l', and 'o'.

We use single quotes or double quotes to represent a string in Python.


For example,

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'
Here, we have created a string variable named string1. The variable is
initialized with the string Python Programming.

Example: Python String


# create string type variables

name = "Python"
print(name)

message = "I love Python."


print(message)
Run Code
Output

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:

We can access the characters in a string in three ways.

Indexing: One way is to treat strings as a list and use index values.
For example,
greet = 'hello'

# access 1st index element


print(greet[1]) # "e"

Negative Indexing: Similar to a list, Python allows negative indexing


for its strings. For example,
greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"

Slicing: Access a range of characters in a string by using the slicing


operator colon :. For example,
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"

Note: If we try to access an index out of the range or use numbers


other than an integer, we will get errors.

Python Strings are immutable:


In Python, strings are immutable. That means the characters of a
string cannot be changed. For example,

message = 'Hola Amigos'


message[0] = 'H'
print(message)

Output

TypeError: 'str' object does not support item assignment


However, we can assign the variable name to a new string. For
example,

message = 'Hola Amigos'

# assign new string to message variable


message = 'Hello Friends'

prints(message); # prints "Hello Friends"

Python Multiline String:

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

Never gonna give you up


Never gonna let you down
In the above example, anything inside the enclosing triple-quotes is
one multiline string.

Python String Operations:

There are many operations that can be performed with strings which
makes it one of the most used data types in Python.

1. Compare Two Strings


We use the == operator to compare two strings. If two strings are
equal, the operator returns True. Otherwise, it returns False. For
example,

str1 = "Hello, world!"


str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Run Code
Output

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.

2. Join Two or More Strings


In Python, we can join (concatenate) two or more strings using the +
operator.

greet = "Hello, "


name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


Run Code
In the above example, we have used the + operator to join two strings:
greet and name.

Python String Length:

In Python, we use the len() method to find the length of a string. For
example,

greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5

String Membership Test:

We can test if a substring exists within a string or not, using the


keyword in.

print('a' in 'program') # True


print('at' not in 'battle') False
Run Code
Methods of Python String
Besides those mentioned above, there are various string methods
present in Python. Here are some of those methods:

Methods Description

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

find() returns the index of first occurrence of substring

rstrip() removes trailing characters

split() splits string from left

startswith() checks if string starts with the specified string

isnumeric() checks numeric characters

index() returns index of substring


Escape Sequences in Python

The escape sequence is used to escape some of the characters present


inside a string.

Suppose we need to include both double quote and single quote inside
a string,

example = "He said, "What's there?""

print(example) # throws error


Run Code
Since strings are represented by single or double quotes, the compiler
will treat "He said, " as the string. Hence, the above code will cause
an error.

To solve this issue, we use the escape character \ in Python.

# escape double quotes


example = "He said, \"What's there?\""

# escape single quotes


example = 'He said, "What\'s there?"'

print(example)
# Output: He said, "What's there?"
Here is a list of all the escape sequences supported by Python.

Escape Sequence Description

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell
\b ASCII Backspace

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage Return

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH

Python String Formatting (f-Strings)


Python f-Strings make it really easy to print values and variables. For
example,

name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}')

Output

Cathy is from UK
Here, f'{name} is from {country}' is an f-string.

Python Sets

A set is a collection of unique data. That is, elements of a set cannot


be duplicate. For example,
Suppose we want to store information about student IDs.
Since student IDs cannot be duplicate, we can use a set.
Create a Set in Python

In Python, we create sets by placing all the elements inside curly


braces {}, separated by comma.
A set can have any number of items and they may be of different
types (integer, float, tuple, string etc.). But a set cannot have mutable
elements like lists, sets or dictionaries as its elements.
Let's see an example,
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type


vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

# create a set of mixed data types


mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

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.

Create an Empty Set in Python


Creating an empty set is a bit tricky. Empty curly braces {} will make
an empty dictionary in Python.
To make a set without any elements, we use the set() function without
any argument. For example,
# create an empty set
empty_set = set()

# create an empty dictionary


empty_dictionary = { }

# check data type of empty_set


print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set


print('Data type of empty_dictionary', type(empty_dictionary))

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.

Duplicate Items in a Set


Let's see what will happen if we try to include duplicate items in a set.
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Here, we can see there are no duplicate items in the set as a set cannot
contain duplicates.
Add and Update Set Items in Python
Sets are mutable. However, since they are unordered, indexing has no
meaning.
We cannot access or change an element of a set using indexing or
slicing. Set data type does not support it.

Add Items to a Set in Python


In Python, we use the add() method to add an item to a set. For
example,
numbers = {21, 34, 54, 12}

print('Initial Set:',numbers)

# using add() method


numbers.add(32)

print('Updated 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.

Update Python Set


The update() method is used to update the set with items other
collection types (lists, tuples, sets, etc). For example,
companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']

companies.update(tech_companies)

print(companies)
# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Here, all the unique elements of tech_companies are added to


the companies set.

Remove an Element from a Set


We use the discard() method to remove the specified element from a
set. For example,
languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set


removedValue = languages.discard('Java')

print('Set after remove():', 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.

Returns an enumerate object. It contains the index and value f


enumerate()
all the items of the set as a pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

Returns a new sorted list from elements in the set(does not so


sorted()
the set itself).

sum() Returns the sum of all elements in the set.


Find Number of Set Elements
We can use the len() method to find the number of elements present in
a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)

# find number of elements


print('Total Elements:', len(even_numbers))

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.

Python Set Operations


Python Set provides different built-in methods to perform
mathematical set operations like union, intersection, subtraction, and
symmetric difference.
Union of Two Sets
The union of two sets A and B include all the elements of
set A and B.

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}

# perform union operation using |


print('Union using |:', A | B)

# perform union operation using union()


print('Union using union():', A.union(B))

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}

# perform intersection operation using &


print('Intersection using &:', A & B)

# perform intersection operation using intersection()


print('Intersection using intersection():', A.intersection(B))

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}

# perform difference operation using &


print('Difference using &:', A - B)

# perform difference operation using difference()


print('Difference using difference():', A.difference(B))

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}

# perform difference operation using &


print('using ^:', A ^ B)

# 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}

# perform difference operation using &


if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')

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

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

Returns the difference of two or more sets as


difference()
a new set

Removes all elements of another set from this


difference_update()
set

Removes an element from the set if it is a


discard() member. (Do nothing if the element is not in
set)

Returns the intersection of two sets as a new


intersection()
set

Updates the set with the intersection of itself


intersection_update()
and another

Returns True if two sets have a null


isdisjoint()
intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty
Removes an element from the set. If the
remove()
element is not a member, raises a KeyError

Returns the symmetric difference of two sets


symmetric_difference()
as a new set

Updates a set with the symmetric difference


symmetric_difference_update()
of itself and another

union() Returns the union of sets in a new set

Updates the set with the union of itself and


update()
others

Python Dictionary

In Python, a dictionary is a collection that allows us to store data


in key-value pairs

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"
}

# printing the dictionary


print(country_capitals)

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)

Tip: We can also use Python's dict() function to create dictionaries.

Python Dictionary Length


We can get the size of a dictionary by using the len() function.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}

# get dictionary's length


print(len(country_capitals)) # 3
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside
square brackets.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}

print(country_capitals["United States"]) # Washington D.C.

print(country_capitals["England"]) # London

Note: We can also use the get() method to access dictionary items.

Change Dictionary Items


Python dictionaries are mutable (changeable). We can change the
value of a dictionary element by referring to its key. For example,
country_capitals = {
"United States": "Washington D.C.,
"Italy": "Naples",
"England": "London"
}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

print(country_capitals)

Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England':
'London'}

Add Items to a Dictionary


We can add an item to the dictionary by assigning a value to a new
key (that does not exist in the dictionary). For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}

# add an item with "Germany" as key and "Berlin" as its value


country_capitals["Germany"] = "Berlin"

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.

Remove Dictionary Items


We use the del statement to remove an element from the dictionary.
For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}

# delete item having "United States" key


del country_capitals["United States"]

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) # {}

Python Dictionary Methods


Here are some of the commonly used dictionary methods.
Function Description

pop() Remove the item with the specified key.

update() Add or change dictionary items.

clear() Remove all the items from the dictionary.

keys() Returns all the dictionary's keys.

values() Returns all the dictionary's values.

get() Returns the value of the specified key.

popitem() Returns the last inserted key and value as a tuple.

copy() Returns a copy of the dictionary.

Dictionary Membership Test


We can check whether a key exists in a dictionary using
the in operator.
my_list = {1: "Hello", "Hi": 25, "Howdy": 100}

print(1 in my_list) # True

# the not in operator checks whether key doesn't exist


print("Howdy" not in my_list) # False
print("Hello" in my_list) # False

Note: The in operator checks whether a key exists; it doesn't check


whether a value exists or not.

You might also like