[Go to site: main page, start]

0% found this document useful (0 votes)
2 views37 pages

Python Notes

python is good

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Python Notes

python is good

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python unit 1

[Link](Computer Science) (Thiruvalluvar University)

messages.pdf_cover_qr_code_label

messages.downloaded_
messages.studocu_not_sponsored_or_endorsed_by_college

messages.downloaded_
UNIT 1

Python: Introduction – Numbers – Strings – Variables - Lists – Tuples – Dictionaries - Sets


- Comparison.

1. INTRODUCTION

What is Python

• Python is a general-purpose, dynamic, high-level, and interpreted programming


language.
• It supports Object Oriented programming approach to develop applications.
• It is simple and easy to learn and provides lots of high-level data structures.
• Python is a programming language that lets you work quickly and integrate systems
more efficiently.
• It is used for web development,software development,mathematics,system scripting

Python Features

Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed below a
few essential features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward and much the same as the English language.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.

3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc.

messages.downloaded_
5) Free and Open Source

Python is freely available for everyone. It is freely available on its official


website [Link]. It has a large community across the world that is dedicatedly
working towards make new python modules and functions. Anyone can contribute to the
Python community. The open-source means, "Anyone can download its source code
without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc.

7) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc.

9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.

10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable

The code of the other programming language can use in the Python source code. We can
use Python source code in another programming language as well. It can embed other
language into our code.

12. Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.

Python History and Versions


o Python laid its foundation in the late 1980s.

messages.downloaded_
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to [Link].
o In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage
collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python
language, which was capable of Exception Handling and interfacing with the
Amoeba Operating System.

Python Applications:

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser, etc.

messages.downloaded_
2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface.

3) Console-based Application

Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute.

4) Software Development

Python is useful for the software development process. It works as a support language and
can be used to build control and management, testing, etc.

5) Scientific and Numeric

This is the era of Artificial intelligence where the machine can perform the task the same as
the human. Python language is the most suitable language for Artificial intelligence or
machine learning. It consists of many scientific and mathematical libraries, which makes
easy to solve complex calculations.

6) Business Applications

Business Applications differ from standard applications. E-commerce and ERP are an
example of a business application. This kind of application requires extensively, scalability
and readability, and Python provides all these features.

7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python are TimPlayer,
cplay, etc. The few multimedia libraries are given below.

o Gstreamer
o Pyglet
o QT Phonon

(8)Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

messages.downloaded_
2. Numbers in python

o The number data types are used to store the numeric values inside the variables.
Number objects are created when some value is assigned to a variable. For example,
a = 5 will create a number object a with value 5.
o Int (signed Integer object) : they are the negative or non-negative numbers with no
decimal point. There is no limit on an integer in python.
1. float(floatingpointnumbers) :
The float type is used to store the decimal point (floating point) numbers. In
python, float may also be written in scientific notation representing the power of
10. for example, 2.5e2 represents the value 250.0.
• Complex(complexnumbers)
Complex numbers are of the form a+bj where a is the real part of the number and bj
is the imaginary part of the number. The imaginary i is nothing but the square root of
-1. It is not as much used in the programming.

Number type conversion:

The various types of numbers like int, float, complex are also as the functions in python. It is
similar to the wrapper classes of Java which is mostly used for typecasting.

There are the following functions which are used to perform type conversion.

o int (a) converts a to integer.


o float(a) converts a to float.
o complex(a) converts a to complex.
o complex (a,b) converts a and b to complex numbers with real part a and imaginary
part b.

Example

i="123456"
print(type(i))
num = int(i)
print(num)
print(type(num))
j = 190.98
print(int(j));

Output:

messages.downloaded_
<class 'str'>
123456
<class 'int'>
190

Python Number functions

There are various in-built functions which can be directly used to perform various
calculations on the numbers defined in the program.

Function Description
abs(x) The (positive) distance between x and 0.
ciel(x) The ceiling value of x, i.e., the smallest integer that is not less than x.
cmp(x,y) Compares x and y. It returns 0 if x == y, -1 if x<y, 1 if x > y.
exp(x) The exponent of x that is ex.
fabs(x) The absolute value of x.
floor(x) The floor value of x, i.e., the greatest integer that is less than x.
log(x) The natural log value of x.
log10(x) The base 10 log of x is returned.
max(x1,x2 The maximum of the sequence is returned.
,......)
min(x1,x2, The minimum of the sequence is returned.
.. . .)
modf(x1,x A tuple is returned containing the fractional and integer parts of a floating point
2,........) number. The integer part is also returned as a float.
pow(x,y) Returns x ** y.
round(x[, The value of x is rounded to n digits.
n])
sqrt(x) The square root of x is retuned.

3. Python String

➢ Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.

➢ The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.

➢ Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.

messages.downloaded_
Syntax:

str = "Hi Python !"

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes.


Python also provides triple-quotes to represent the string, but it is generally used for
multiline string or docstrings.

str1 = 'Hello Python'


print(str1)

#Using double quotes


str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for represent the multiline or docstring'''
print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Strings indexing spliṄng

Like other languages, the indexing of the Python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.

messages.downloaded_
Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range

splitting

• the slice operator [] is used to access the individual characters of the string.
• However, we can use the : (colon) operator in Python to access the substring from
the given string. Consider the following example.

messages.downloaded_
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing
else.

Consider the following example: str

= "JAVATPOINT"
print(str[0:])
print(str[1:5])
print(str[2:4])
print(str[:3])
print(str[4:7])

Output:

JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string;

it starts from the rightmost character, which is indicated as -1. The second rightmost index
indicates -2, and so on. Consider the following image.

messages.downloaded_
Consider the following example

1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:

T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Reassigning Strings

Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new string
since its content cannot be partially replaced. Strings are immutable in Python.

Example
1. str = "HELLO"

messages.downloaded_
2. print(str)
3. str = "hello"
4. print(str)

Output:

HELLO
hello

Deleting the String

As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.

1. str = "JAVATPOINT"
2. del str[1]

Output:

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

str1 = "JAVATPOINT"

del str1

print(str1)

NameError: name 'str1' is not defined

format() method

• The format() method is the most flexible and useful method in formatting strings.
• The curly braces {} are used as the placeholder in the string and replaced by
the format() method argument. Let's have a look at the given an example:

1. # Using Curly braces


2. print("{} and {} both are the best friend".format("Devansh","Abhishek"))
3.
4. #Positional Argument
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument

messages.downloaded_
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

STRING METHODS
• Python String capitalize()

This method returns a copy of the original string and converts the first character of the string to
a capital (uppercase) letter, while making all other characters in the string lowercase letters.

Eg

name = "geeks FOR geeks"

print([Link]())

output:

Geeks for geeks

• String count()

This function is an inbuilt function in Python programming language that returns the number of
occurrences of a substring in the given string. In this article, we will explore the details of
the count() method

Eg

my_string = "GeeksForGeeks" char_count =


my_string.count('e') print(char_count)

output 4
Python String islower()

This method checks if all characters in the string are lowercase. Eg

messages.downloaded_
print("geeks".islower())

output:

True

Python String isupper()

This method returns whether all characters in a string are uppercase or not.

Eg

print(("GEEKS").isupper())

output:

True

Python join()

This is an inbuilt string function in Python used to join elements of the sequence separated
by a string separator. This function joins elements of a sequence and makes it a string.

Example:

str = '-'.join('hello')

print(str)

Output:

h-e-l-l-o

Python String lower()


This method converts all uppercase characters in a string into lowercase characters and
returns it. In this article, we will cover how lower() is used in a program to convert
uppercase to lowercase in Python.

Eg

text = 'GeEks FOR geeKS'

print("Original String:")
print(text)

messages.downloaded_
print("\nConverted String:")
print([Link]())

Output:

Original String:
GeEks FOR geeKS

Converted string:
geeks for geeks

Python String swapcase()

This method converts all uppercase characters to lowercase and vice versa of the given
string and returns it.
Eg
string = "gEEksFORgeeks"
print([Link]())
string = "geeksforgeeks"
print([Link]())
string = "GEEKSFORGEEKS"
print([Link]())

Output:

GeeKSforGEEKS
GEEKSFORGEEKS

Python String upper()

This method converts all lowercase characters in a string into uppercase characters and
returns it. In this article, we’ll explore Python’s upper() method in-depth

Eg

original_text = "geeks for geeks"

uppercase_text = original_text.upper()

print(uppercase_text)

output:

GEEKS FOR GEEKS

messages.downloaded_
4. Python Variables

✓ Python Variable is containers that store values.


✓ A Python variable is a name given to a memory location. It is the basic unit of storage
in a program.

Rules for Python variables

• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
• The reserved words(keywords) in Python cannot be used to name the variable in
Python.

Variables Assignment in Python

• Here, we have assigned a number, a floating point number, and a string to a variable
such as age, salary, and name.

age = 45
salary = 1456.8
name = "John"
print(age)
print(salary)
print(name)

Output:

45
1456.8
John

Global and Local Variables

✓ Local variables in Python are the ones that are defined and declared inside a
function.
We can not call this variable outside the function.

# This function uses global variable s

messages.downloaded_
def f():
s = "Welcome geeks"
print(s)
f()

Output:

Welcome geeks

✓ Global variables in Python are the ones that are defined and declared outside a
function, and we need to use them inside a function.

# This function has a variable


with # name same as s.
def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Output:

I love Geeksforgeeks

5. Python List:

✓ A list is a collection of items separated by commas and denoted by the symbol [].
A list is a collection of different kinds of values or items.

✓ Since Python lists are mutable, we can change their elements after forming.
✓ The comma (,) and the square brackets [enclose the List's items] serve as separators.

List Declaration
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
print(list1)
print(list2)
print(type(list1))
print(type(list2))

messages.downloaded_
Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

Characteristics of Lists

The characteristics of the List are as follows:

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Ordered List Checking


1. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
2. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
3. a == b

Output:

False

List Indexing and Splitting

✓ The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.

✓ The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.

We can get the sub-list of the list using the following syntax.

1. list_varible(start:stop:step)
o The beginning indicates the beginning record position of the rundown.
o The stop signifies the last record position of the rundown.

messages.downloaded_
o Within a start, the step is used to skip the nth element: stop.

The start parameter is the initial index, the step is the ending index, and the value of the end
parameter is the number of elements that are "stepped" through. The default value for the
step is one without a specific value. Inside the resultant Sub List, the same with record start
would be available, yet the one with the file finish will not. The first element in a list appears
to have an index of zero.

list = [1,2,3,4,5,6,7]

1. print(list[0])
2. print(list[1])
3. print(list[2])
4. print(list[3])
5. print(list[0:6])
6. print(list[:])
7. print(list[2:5])
8. print(list[1:6:2])

Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

# negative indexing example

1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])

messages.downloaded_
Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item
in the List was returned by the first print statement in the code above. The second print
statement returned the sub-list, and so on.

Updating List Values

Due to their mutability and the slice and assignment operator's ability to update their values,
lists are Python's most adaptable data structure. Python's append() and insert() methods
can also add values to a list.

Consider the following example to update the values inside the List.

Code

1. # updating list values


2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10. # It will add value at the end of the list
11. list[-1] = 25
12. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.

messages.downloaded_
Consider the following example to delete the list elements.

Code

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

1. Repetition

The redundancy administrator empowers the rundown components to be rehashed on


different occasions.

1. list1 = [12, 14, 16, 18, 20]


2. l = list1 * 2
3. print(l)

messages.downloaded_
Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation

It concatenates the list mentioned on either side of the operator.

Code

1. # concatenation of two lists


2. # declaring the lists
3. list1 = [12, 14, 16, 18, 20]
4. list2 = [9, 10, 32, 54, 86]
5. # concatenation operator +
6. l = list1 + list2
7. print(l)

Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length

It is used to get the length of the list Eg

list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]

len(list1)

Output:

4. Iteration

The for loop is used to iterate over the list elements.

Code

1. # iteration of the list


2. # declaring the list
3. list1 = [12, 14, 16, 39, 40]

messages.downloaded_
4. # iterating
5. for i in list1:
6. print(i)

Output:

12
14
16
39
40

5. Membership

It returns true if a particular item exists in a particular list otherwise false.

Code

1. # membership of the list


2. # declaring the list
3. list1 = [100, 200, 300, 400, 500]
4. # true will be printed if value exists
5. # and false if not
6.
7. print(600 in list1)
8. print(700 in list1)
9. print(1040 in list1)
10.
11. print(300 in list1)
12. print(100 in list1)
13. print(500 in list1)

Output:

False
False
False
True
True
True

Python List Built-in Functions

messages.downloaded_
Python provides the following built-in functions, which can be used with the lists.

1. len()
2. max()
3. min()

len( )

It is used to calculate the length of string

1. list1 = [12, 16, 18, 20, 39, 40]


2. len(list1)

Output:

Max( )

It returns the maximum element of the list

1. list1 = [103, 675, 321, 782, 200]


2. print(max(list1))

Output:

782

Min( )

It returns the minimum element of the list

1. list1 = [103, 675, 321, 782, 200]


2. print(min(list1))

Output:

103

6. Tuple

Tuples are used to store multiple items in a single variable.

messages.downloaded_
Tuple is one of 4 built-in data types in Python used to store collections of dataA tuple is a
collection which is ordered and unchangeable.

Tuples are written with round brackets.

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Example
tuple = ("apple", "banana", "cherry")
print(tuple)

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

• Using a positive index

• Using a negative index

Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

var = ("Geeks", "for", "Geeks")

print("Value in Var[0] = ", var[0])

print("Value in Var[1] = ", var[1])

print("Value in Var[2] = ", var[2])

Output:

Value in Var[0] = Geeks


Value in Var[1] = for
Value in Var[2] = Geeks

messages.downloaded_
Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we
will use the negative index within [].

var = (1, 2, 3)

print("Value in Var[-1] = ", var[-1])

print("Value in Var[-2] = ", var[-2])

print("Value in Var[-3] = ", var[-3])

Output:

Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

• Concatenation

• Nesting

• Repetition

• Slicing

• Deleting

• Finding the length

• Multiple Data Types with tuples

• Conversion of lists to tuples

• Tuples in a Loop

Concatenation of Python Tuples

To Concatenation of Python Tuples, we will use plus operators(+).

messages.downloaded_
Eg

tuple1 = (0, 1, 2, 3)

tuple2 = ('python',

'geek') print(tuple1 +

tuple2)

Output:

(0, 1, 2, 3, 'python', 'geek')

Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that tuple.

Eg

tuple3 =
Output:
('python',)*3
('python', 'python', 'python')
print(tuple3)

Dictionary

• Dictionaries are used to store data values in key:value pairs.


• A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
• Dictionaries are written with curly brackets, and have keys and values:

Eg:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

• Using a positive index

• Using a negative index

messages.downloaded_
Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python. var =

("Geeks", "for", "Geeks")

print("Value in Var[0] = ", var[0])

print("Value in Var[1] = ", var[1])

print("Value in Var[2] = ", var[2])

Output:

Value in Var[0] = Geeks


Value in Var[1] = for
Value in Var[2] = Geeks

Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].

var = (1, 2, 3)

print("Value in Var[-1] = ", var[-1])

print("Value in Var[-2] = ", var[-2])

print("Value in Var[-3] = ", var[-3])

Output:

Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

• Concatenation

messages.downloaded_
• Nesting

• Repetition

• Slicing

• Deleting

7. Dictionary

• Dictionaries are used to store data values in key:value pairs.


• A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
• Dictionaries are written with curly brackets, and have keys and values:

Example

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

Example

Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same result:

Adding elements to a Dictionary

• Addition of elements can be done in multiple ways.


• One value at a time can be added to a Dictionary by defining value along with the
key

messages.downloaded_
Eg

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}

print(type(Employee))

print("printing Employee data............")

print(Employee)

print("Enter the details of the new employee..........");

Employee["Name"] = input("Name: ");

Employee["Age"] = int(input("Age: "));

Employee["salary"] = int(input("Salary: "));

Employee["Company"] = input("Company:");

print("printing the new data");

print(Employee)

Output

<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the
details of the new employee....
Name: Sunny Age:
38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}

Deleting Elements using del Keyword

messages.downloaded_
The items of the dictionary can be deleted by using the del keyword as given below.

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data......")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output

<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary:
Employee Lets try to print it again
NameError: name 'Employee' is not defined.

8. Python Set

A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.

Creating a set

A set is created by using the set() function or placing all the elements within a pair of curly
braces.

Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}

messages.downloaded_
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)

Output

When the above code is executed, it produces the following result. Please note how the
order of the elements has changed in the result.

set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])


set(['Jan', 'Mar', 'Feb'])
set([17, 21, 22])

Accessing Values in a Set

We cannot access individual values in a set. We can only access all the elements together as
shown above. But we can also get a list of individual elements by looping through the set.

Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])

for d in Days:
print(d)

Output

When the above code is executed, it produces the following result −

Wed
Sun
Fri
Tue
Mon
Thu
Sat

Adding Items to a Set

We can add elements to a set by using add() method. Again as discussed there is no specific
index attached to the newly added element.

Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

messages.downloaded_
[Link]("Sun")
print(Days)

Output

When the above code is executed, it produces the following result −

set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Removing Item from a Set

We can remove elements from a set by using discard() method. Again as discussed there is
no specific index attached to the newly added element.

Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

[Link]("Sun")
print(Days)

Output

When the above code is executed, it produces the following result.

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Union of Sets

The union operation on two sets produces a new set containing all the distinct elements
from both the sets. In the below example the element “Wed” is present in both the sets.

Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)

Output

When the above code is executed, it produces the following result. Please note the result
has only one “wed”.

messages.downloaded_
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Intersection of Sets

The intersection operation on two sets produces a new set containing only the common
elements from both the sets. In the below example the element “Wed” is present in both
the sets.

Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)

Output

When the above code is executed, it produces the following result. Please note the result
has only one “wed”.

set(['Wed'])

Difference of Sets

The difference operation on two sets produces a new set containing only the elements from
the first set and none from the second set. In the below example the element “Wed” is
present in both the sets so it will not be found in the result set.

Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)

Output

When the above code is executed, it produces the following result. Please note the result
has only one “wed”.

set(['Mon', 'Tue'])

9. set comparisons:

Set Membership Check

messages.downloaded_
In set we can check if the element exist in the set or not.

Example:
set_1 = {1,2,3,4,5}
print(1 in set_1)
print(5 not in set_1)

Output:

True
False

2. Set Equivalent Check

We use this operation to check whether two sets are equivalent to each other or not.

Example:
set_1 = {1,2,3,4,5}
set_2 = {1,2,3,4,5}

print(set_1 == set_2)
print(set_1 != set_2)

Output:

True
True

3. Subset Check

A subset is a set that entirely exists within another. We use this operator to check whether
S1 is the subset of S2 or not.

Example:
set_1 = {1,2,3,4}
set_2 = {3,4,5,6}
print(set_1.issubset(set_2))

Output: False

4. Superset Check

A superset is the opposite of a subset. A set is declared as a superset if all elements of the
another set exist within it.

messages.downloaded_
Example:
set_1 = {1,2,3,4}
set_2 = {3,4}
print(set_1.issuperset(set_2))

Output: True

messages.downloaded_

You might also like