Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-Python Programming- Second Draft

CU-MCA-Python Programming- Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-10-12 04:11:27

Description: CU-MCA-Python Programming- Second Draft

Search

Read the Text Version

MASTER OF COMPUTER APPLICATIONS PYTHON PROGRAMMING

CHANDIGARH UNIVERSITY Institute of Distance and Online Learning Course Development Committee Prof. (Dr.) R.S.Bawa Pro Chancellor, Chandigarh University, Gharuan, Punjab Advisors Prof. (Dr.) Bharat Bhushan, Director – IGNOU Prof. (Dr.) Majulika Srivastava, Director – CIQA, IGNOU Programme Coordinators & Editing Team Master of Business Administration (MBA) Bachelor of Business Administration (BBA) Coordinator – Dr. Rupali Arora Coordinator – Dr. Simran Jewandah Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA) Coordinator – Dr. Raju Kumar Coordinator – Dr. Manisha Malhotra Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.) Coordinator – Dr. Aman Jindal Coordinator – Dr. Minakshi Garg Master of Arts (Psychology) Bachelor of Science (Travel &Tourism Management) Coordinator – Dr. Samerjeet Kaur Coordinator – Dr. Shikha Sharma Master of Arts (English) Bachelor of Arts (General) Coordinator – Dr. Ashita Chadha Coordinator – Ms. Neeraj Gohlan Academic and Administrative Management Prof. (Dr.) R. M. Bhagat Prof. (Dr.) S.S. Sehgal Executive Director – Sciences Registrar Prof. (Dr.) Manaswini Acharya Prof. (Dr.) Gurpreet Singh Executive Director – Liberal Arts Director – IDOL © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the authors and the publisher. SLM SPECIALLY PREPARED FOR CU IDOL STUDENTS Printed and Published by: TeamLease Edtech Limited www.teamleaseedtech.com CONTACT NO:- 01133002345 For: CHANDIGARH UNIVERSITY Institute of Distance and Online Learning 2 CU IDOL SELF LEARNING MATERIAL (SLM)

First Published in 2021 All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by any means, without permission in writing from Chandigarh University. Any person who does any unauthorized act in relation to this book may be liable to criminal prosecution and civil claims for damages. This book is meant for educational and learning purpose. The authors of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the event the Authors has/ have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action. 3 CU IDOL SELF LEARNING MATERIAL (SLM)

CONTENT Unit - 1: Introduction To Python And Basics......................................................................... 5 Unit - 2: Introduction To Python Data Structures................................................................. 27 Unit - 3: Flow Control Constructs ....................................................................................... 59 Unit - 4: Functions .............................................................................................................. 84 Unit - 5: Classes ................................................................................................................ 109 Unit - 6: Python For Data Analysis And Visualization 1.................................................... 139 Unit - 7: Python For Data Analysis And Visualization Ii ................................................... 157 Unit - 8: Python For Data Analysis And Visualization Iii .................................................. 176 Unit - 9: Graphical Exploratory Data Analysis (Eda) 1 ...................................................... 219 Unit - 10: Graphical Exploratory Data Analysis (Eda) Ii.................................................... 235 Unit - 11: Quantitative Exploratory Data Analysis (Eda) ................................................... 252 Unit - 12: Statistics 1......................................................................................................... 261 Unit - 13: Statistics Ii ........................................................................................................ 281 Unit - 14: Web Application 1 ............................................................................................ 294 Unit - 15: Web Application 2 ............................................................................................ 302 4 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 1: INTRODUCTION TO PYTHON AND BASICS Structure 1.0. LearningObjectives 1.1. Introduction 1.2. Setting up the Program Environment 1.3. Keywords and Identifiers 1.4. Variables 1.5. Data types 1.6. Dynamic Types 1.7. Summary 1.8. Keywords 1.9. Learning Activity 1.10 Unit End Questions 1.11References 1.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Outline the basics of Python programming language  Summarize the strengths and weakness of Python  Use the IDLE IDE for writing Python programs  Summarize the various data types available in Python  Illustrate the concept of Dynamic types 1.1 INTRODUCTION Python is a popular general-purpose, high-level programming language. Guido van Rossum founded it in 1991, and the Python Software Foundation continued to grow it. It was developed with code readability in mind, and its syntax helps programmers to articulate their ideas with fewer lines of code. Python is a programming language that permits you to work easily and integrate programmes more efficiently. Features of Python 5 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 1.1: Features of Python (Source www.beginnersbook.com) 1. Readable: Python is a very readable language. 2. Easy to Learn: Python is a simple programming language to learn because it is expressive and high level, which means it is simple and easy to code and therefore simple to master. 3. Free: Python can be downloaded and used for free. This means that you can use it in your apps for free after you download it. Python is an example of FOSS (Free Open-Source Software), which means that it is convenient to swap versions of it, read the source code, and changes it. 4. Cross platform: Python is available and can run on various operating systems such as Mac, Windows, Linux, Unix etc. This makes it a cross platform and portable language. 5. Open Source: Python is an open-source programming language. 6. Automatic memory management: Adaptive memory protection is provided by Python, which ensures the memory is instantly deleted and freed. You are not expected to clear the memory. 7. Large standard library: Python has a broad standard library and some useful codes and methods that we can utilize when writing code in Python. 8. Supports exception handling: An exception is an occurrence that can happen during the execution of a code and interrupt the natural flow of the code. Python provides exception handling, which helps one to write less error-prone code and evaluate different conditions that could result in a run time error later on. 9. Advanced features: Supports generators and list comprehensions. APPLICATIONS OF PYTHON 6 CU IDOL SELF LEARNING MATERIAL (SLM)

There is variety of applications of Python; A few of them are listed here. 1. Web development: Python is the foundation of web frameworks such as Django and Flask. They assist you in writing server-side code that allows you to handle databases, generate backend programming concept, and chart URLs, and so on. 2. Machine learning: Python is used to write many machine learning programmes. Machine learning is a method of writing logic that allows a machine to understand and solve a specific problem on its own. Brand reviews on websites like Amazon, Flipkart, eBay, and others, for example, are built on a machine learning model that identifies the user's preferences. Face and speech recognition in your computer is another illustration of machine learning. 3. Data Analysis: Data analysis and data visualisation in form of charts can also be developed using Python. 4. Scripting: Scripting is the procedure of building small programs that automate basic tasks such as submitting automatic response emails. Python programming language can also be used to build those programs. 5. Game development: Development of games can be done using Python. 6. Desktop applications: You can develop desktop application in Python using library like TKinter or QT. STRENGHS: Easy to Read, Learn and Write: Python is a high-level programming language with syntax similar to English. This makes the code easy to familiarize and comprehend. In addition, with respect to other major languages, we prefer fewer lines of code to execute the same operation. Improved Productivity: Python is a very effective programming language. Since Python is so easy, developers can concentrate on solving the problem. They do not need to waste a lot of time learning the grammar or behaviour of the programming language. Interpreted Language: Python is an interpreted language, which means that the code is executed line by line. In the event of a mistake, it suspends further execution and declares the error. And if the software includes several bugs, Python reveals just one. This encourages debugging. 7 CU IDOL SELF LEARNING MATERIAL (SLM)

Dynamically Typed: The data types of variables in Python are not fixed until the code is executed. During execution, it assigns the appropriate data type automatically. The coder is not forced to declare variables or their data types. Vast Libraries Support: The standard library of Python is huge, most of the functions required for your project are available. So, you don’t have to depend on external libraries. Portability: Many programming languages, such as C/C++, need you to modify the code in order to execute the software on various platforms. Python, on the other hand, is not the same. You just need to write it once and then run it somewhere. You can, however, take note not to have any system-dependent functionality. WEAKNESSES: Speed: Python is slower than C or C++. But of course, Python is a high-level language, unlike C or C++ it's not closer to hardware. Mobile Development: Python is a poor choice for mobile apps. It is regarded as a poor option for mobile computing. Memory Consumption: Python is not a good choice for tasks that need a lot of memory. Python's memory utilisation is also high due to the simplicity of the data-types. Database Access: Python has drawbacks when it comes to database access. As comparing to common technology such as JDBC and ODBC, Python's database access layer is found to be somewhat underdeveloped and basic. It cannot, however, be used in industries that require the seamless interaction of complex legacy data. Runtime Errors: Python programmers raised some questions about the language's architecture. Since the language is dynamically typed, it necessitates further checking and includes errors that occur only at runtime. 1.2 SETTING UP PROGRAMMING ENVIRONMENT Getting Python The most up-to-date and current source code, binaries, documentation, news, etc., is available 8 CU IDOL SELF LEARNING MATERIAL (SLM)

on the official website of Python https://www.python.org/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. Installing Python Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. UNIX and Linux Installation Here are the simple steps to install Python on Unix/Linux machine.  Open a Web browser and go to https://www.python.org/downloads/.  Follow the link to download zipped source code available for Unix/Linux.  Download and extract files.  Editing the Modules/Setup file if you want to customize some options.  run. /configure script  make  make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python. Windows Installation Here are the steps to install Python on Windows machine.  Open a Web browser and go to https://www.python.org/downloads/.  Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.  To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.  Run the downloaded file. This brings up the Python install wizard, which is really 9 CU IDOL SELF LEARNING MATERIAL (SLM)

easy to use. Just accept the default settings, wait until the install is finished, and you are done. Setting up PATH Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). Setting path at Windows To add the Python directory to the path for a particular session in Windows − At the command prompt − type path %path%;C:\\Python and press Enter. Note − C:\\Python is the path of the Python directory IDLE IDE: Python's IDLE stands for Integrated Development and Learning Environment. IDLE was built entirely in Python using the tkinter Interface toolkit, and it is also platform neutral, running equally on Windows, Unix, and macOS. Python IDLE comes included in Python installations on Windows and Mac. If you use Linux, you should be able to find and download Python IDLE through your package manager. When IDLE needs to start a new block, it will automatically indent our code. This usually occurs after we use a colon (:). When we press the enter key preceding the colon, our cursor will move a predetermined number of spaces, and a new code block will start. In the settings, we can specify the number of spaces the cursor moves, usually default is four spaces. Python's creators settled on a standard style for well-written Python code, which includes indentation, whitespace, and other guidelines. When developing code for a major project or a complicated problem, we would spend a considerable number of hours writing out all of the required code. 10 CU IDOL SELF LEARNING MATERIAL (SLM)

Code completion saves us time by attempting to finish the code for you. Python IDLE has simple code completion capabilities. It can only autocomplete function and class names. To use auto completion in the editor, simply press the tab key after a text sequence. Call tips will also be given by Python IDLE. A call tip is a clue for a specific portion of your program that helps us familiarize what that feature needs. A call tip will emerge if we do not enter something for a few seconds upon typing the left parenthesis to begin a function call. The Python IDLE file editor's code background functionality is a useful feature. It demonstrates the scope of a function, class, loop, or other construct. This is especially useful when we're scrolling through a long file and need to keep track of where we are in the editor when reviewing code. Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the following prompt: If you are running new version of Python, then you would need to use print statement with parenthesis like print (\"Hello, Python!\"); However, at Python version 2.4.3, this will produce following result: Hello, Python! 11 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 1.2 Interactive Modes in Python Script Mode Programming Invoking the interpreter with a script parameter initiates script execution and proceed till the script is completed. When the script is completed, the interpreter is turned off. Let us write a simple Python program in a script. All python files will have extension .py. So put the following source code in a test.py file. print (\"Hello, Python!\"); Here, assumed that Python interpreter set in PATH variable. Now, run this program as follows: $ python test.py This will produce the following result: Hello, Python! A breakpoint is a line of code that we've described as a location where the interpreter can stop when running our program. They can only function if DEBUG mode is allowed, so make sure you have that enabled first. To set a breakpoint, right-click on the line of code that we want to stop. As a visual indicator of a fixed breakpoint, this will show the line of code in yellow. We can put as many breakpoints as you like in your code. To remove a breakpoint, right-click on the same line again and choose Clear Breakpoint. Once we’ve set our breakpoints and turned-on DEBUG mode, we can run our code as we would normally. The debugger window will pop up, and we can start stepping through our code manually. 12 CU IDOL SELF LEARNING MATERIAL (SLM)

1.3 KEYWORDS AND IDENTIFIERS KEYWORDS In Python, reserved words are referred to as keywords. A keyword cannot be used as a variable name, function name, or other identifier. They are used to describe the Python language's syntax and structure. Keywords in Python are case sensitive. Python 3.7 contains 33 keywords. This count can change slightly over time. Except for True, False, and None, all of the terms are in lowercase and must be written exactly as they are. The list of all the keywords is given below. Table 1.1 Keywords in Python IDENTIFIERS A Python identifier is a name that is used to describe a variable, method, class, module, or other entity in Python. An identifier begins with a alphabets A to Z, or a to z, or a symbol (_), which is proceeded by zero or more characters, underscores, or digits (0 to 9). 13 CU IDOL SELF LEARNING MATERIAL (SLM)

Python doesn't really allow the use of punctuation symbols in identifiers such as @, $, and %. Python is a programming language that is case aware. Thus, in Python, computer and Computer are two distinct identifiers. Here are naming conventions for Python identifiers −  Identifiers may be made up of lowercase (a to z) or uppercase (A to Z) characters, digits (0 to 9), or an underscore.  MyClass, var 1, and print this to screen are all valid cases.  A digit cannot be the first character of an identifier. Variable1 is a true name, but 1variable is not.  Keywords are not permitted to be used as identifiers.  The special symbols like! @, #, $, % etc. are not allowed to be used.  A length is not fixed. Python is a case-sensitive programming language. This means the variable and Variable are not interchangeable. Still assign the identifiers meaningful names. Though c = 10 is a true name, writing count = 10 When you come to the script after a lengthy amount of time, it makes better sense and is easier to figure out what it means. An underscore may be used to distinguish several terms, such as this is a long variable. 1.4VARIABLES A variable is simply an identifier/name that is used to refer to a certain value stored in memory. Since values stored in memory in Python are nothing other than objects, a variable may also be thought of as a reference, referring to a certain object value in memory. While a variable can only refer to one single object value at a time, as the name suggests, a variable can alter and refer to various objects from time to time. For example, number = 10 Here, we have created a variable named number. We have assigned the value 10 to the variable. 14 CU IDOL SELF LEARNING MATERIAL (SLM)

You can think of variables as a bag to store books in it and that book can be replaced at any time. number = 10 number = 1.1 Initially, the value of number was 10. Later, it was changed to 1.1. Example >>website = \"apple.com\" >>print(website) >>apple.com In the above example, we assigned a value apple.com to the variable website. Then, we printed out the value assigned to website i.e., apple.com Since Python is a type-inferred language, you do not need to specify the variable type directly. It recognises that apple.com is a string and declares the website attribute to be a string. Constants A constant is a variable whose value cannot be altered. Constants can be thought of as containers that carry information that cannot be modified later. You can think of constants as a bag to store some books which cannot be replaced once placed inside the bag. Constants in Python can be specified in a module, which is a file that can be imported to access the defined constants and methods. A module constant should be written in uppercase letters, and multi-word constant names should be divided by an underscore (_). Example: constant.py: PI = 3.14 GRAVITY = 9.8 main.py: import constant 15 CU IDOL SELF LEARNING MATERIAL (SLM)

print(constant.PI) print(constant.GRAVITY) Output 3.14 9.8 In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally, we print the constant value. First Python Program >>>print (“Hello! Welcome to Python”) >>>Hello! Welcome to Python 1.5DATA TYPES The data stored in memory can be of many types. Age of a human, for instance, is represented as a numeric number, while the address is represented as alphanumeric characters. Python has a number of common data types that are utilize to narrate the operations that can be performed on them as well as the storage mechanism for each of them. Python has five standard data types 1. Numbers 2. Sequence Type 3. Boolean 4. Set 5. Dictionary 16 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 1.3 Data types in Python (Source: www.javapoint.com) Numbers: Number stores numeric values. The integer, float, and complex values belong to a Python Numbers data-type. Python supports three types of numeric data. 1. int– Integer value can be any length such as integers 10, 23, 29, -20, -15 etc. Python has no restriction on the length of an integer. Its value belongs to int 2. float– Float is used to store floating-point numbers like 13.9, 9.02, 15.92, etc. It is accurate up to 15 decimal points. 3. complex– A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc. Boolean: The Boolean type has two built-in values: True and False. These values are used to decide whether or not the given expression is correct or incorrect. It is represented by the class bool. True can be represented by any non-zero value or ‘T’ whereas false can be represented by either 0 or ‘F’. Dictionary: A dictionary is an unordered set of objects with a key-value pair. It is identical to an associative array or a hash table in that each key stores a unique value. The key can be any primitive data type, while the value can be any Python object. The dictionary elements are 17 CU IDOL SELF LEARNING MATERIAL (SLM)

identified by commas (,) and wrapped in curly braces. Set: Python Set is the data type's unordered collection. It is iterable, mutable (can be changed after creation), and contains distinct elements. The order of the components in set is undefined; it may return the element's modified sequence. The collection is generated by calling the built- in function set (), or by forwarding a sequence of elements enclosed in curly braces and separated by a comma. It can contain various types of values. Sequence Type: String: The string is described as the series of characters enclosed by quotation marks. To describe a string in Python, we may use single, double, or triple quotes. String manipulation in Python is simple since Python has built-in functions and operators for performing string operations. In the case of string handling, the operator + is preferred to concatenate two strings as the operation “Welcome to” +” python” returns “Welcome to python”. List: Python lists are equivalent to arrays in C. The list, contrastingly, will contain data of various sorts. The values in the collection are divided by a comma (,) and are surrounded by square brackets []. Tuple: In several ways, a tuple is identical to a list. Tuples, like lists, contain a set of objects of various data types. The tuple's elements are divided by a comma (,) and enclosed in parentheses (). And we can't change the size or meaning of a tuple's objects, it's a read-only data structure. Input and Output Python has a variety of built-in features that are easily accessible from the Python prompt. Some of the methods, such as input () and print (), are often used for normal input and output activities. We use the print () function to output data to the standard output device (screen). 18 CU IDOL SELF LEARNING MATERIAL (SLM)

In the second print () statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it. Reading Input We will want to accept user input to allow for more usability. In Python, we have the input () method that enables us to do this. The general form for input () is: input([prompt]) Where prompt is the string that we would like to print on the screen. It is optional. Here, we can observe that the provided value 10 is a string, not a number. To change this into a number we can use int () or float () methods 1.6 DYNAMIC TYPES Python is a dynamically typed programming language. This certifies that the Python interpreter only performs type testing at runtime, and that a variable's type will change over time. The explanations below illustrate the concept of dynamic typing.: 19 CU IDOL SELF LEARNING MATERIAL (SLM)

>>>val1 = “Hello” >>>type(val1) <class‘str’> >>>val1 = 28.1 >>>type(val1) <class‘float’> type() returns the type of an object. These examples confirm that the type of val1 is allowed to change, and Python correctly infers the type as it changes. TYPE CONVERSION Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. There are two types of Type Conversion in Python: 1. Implicit Type Conversion 2. Explicit Type Conversion Implicit Type Conversion: The Python interpreter automatically translates one data type to another without any manual intervention in implicit type conversion of data types. To get a clear view of the topic see the examples given below. Example: x = 10 print(\"x is of type:\",type(x)) y = 10.6 print(\"y is of type:\",type(y)) x=x+y print(x) print(\"x is of type:\",type(x)) Output: x is of type: <class 'int'> y is of type: <class 'float'> 20.6 20 CU IDOL SELF LEARNING MATERIAL (SLM)

x is of type: <class 'float'> Explicit Type Conversion: In Python, typecasting is the method of converting one data type to another. To produce good outcomes, we often need to adjust the data type while running such operations. For example, if we want to concatenate an int variable to a string such as (“My age is” + age), it will result in errors since one data type is a string and one is int. The “+” symbol is used in various ways for all data forms. The integer adds another integer, while the string concatenates with another string. As a result, we must specifically instruct Python to add the cast to the data type. Syntax: <required_datatype>(expression) Function Description int(a, base) float() This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string Returns a floating-point number object from a number or string containing digits with decimal point or scientific notation. complex() Returns a complex number with real and imaginary hex() components. oct Converts a decimal integer into a hexadecimal number with 0x ord() prefix. tuple() Converts a decimal integer in an octal representation with 0o set() prefix. list() This function is used to convert a character to integer This function is used to convert to a tuple This function returns the type after converting to set This function is used to convert any data type to a list type Table 1.2 Type Conversion Methods in Python 21 CU IDOL SELF LEARNING MATERIAL (SLM)

1.7 SUMMARY  Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991.  Python code can be executed in Interactive mode and scripting Mode  A Python identifier is a name used to identify a variable, function, class, module or other object  Python has five standard data types :Numbers, Sequence Type, Boolean, Set and Dictionary  Python is a dynamically typed language  Strings in Python are identified as a contiguous set of characters represented in the quotation marks. String is immutable  Type conversion functions to directly convert one data type to another 1.8 KEYWORDS  Script Mode- Invoking the interpreter with a script  Interactive Mode-Invoking the interpreter without passing a script fil  Keywords-Reserved word with specific meaning  Identifiers-name used to identify a variable, function or class  Data types-type of data that can be stored  Dynamic Types-Data Type is known at run time 1.9 LEARNING ACTIVITY 1. Write a Python program to create all possible strings by using 'a', 'e', 'i', 'o', 'u'. Use the characters exactly once. 2. Write a Python program to create the combinations of 3-digit combo 22 CU IDOL SELF LEARNING MATERIAL (SLM)

1.10UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. List any four features /advantages of python. 2. Discuss in about the data types available in python? 3. Why Python is referred as dynamic typed language? 4. Differentiate mutable & immutable data types. 5. Consider the string str=” Python programming”, write the output of the following statements: printstr printstr[0] printstr[1:7] printstr[7:] printstr *2 printstr+”Welcome” 6. What is mean by type conversion? Long Questions 1. Illustrate the features and application of python 2. Discuss about the string handling functions with suitable example. 3. Demonstrate the various operators in python 4. Write a python program to find whether the given string is palindrome or not without using functions 5. Write a program to compute area of the circle B. Multiple Choice Questions 1. What is the maximum possible length of an identifier? a. 31 characters b. 63 characters c. 79 characters d. Identifiers can be of any length. 23 CU IDOL SELF LEARNING MATERIAL (SLM)

2. What will be the output of the following Python code? 24 example = \"snow world\" print(\"%s\" % example[4:7]) a. wo b. world c. sn d. rl 3. Given a string example=\"hello\" what is the output of example.count('l')? a. 2 b. 1 c. 0 d. None 4. What will be the output of the following Python code? example=\"hello\" example.rfind(\"e\") a. -1 b. 4 c. 1 d. None of the above 5. Which of the following is an invalid statement? a. abc = 1,000,000 b. a b c = 1000 2000 3000 c. a,b,c = 1000, 2000, 3000 d. a_b_c = 1,000,000 6. Which of the following statement is correct? a. List is mutable & Tuple is immutable b. List is immutable & Tuple is mutable c. Both are Immutable CU IDOL SELF LEARNING MATERIAL (SLM)

d. Both are Mutable. 25 7. Which of the following variable is invalid? a. __str b. _str c. _str_ d. None of the above 8. Which predefined Python function is used to find length of string? a. length () b. len() c. strlen() d. stringlength() 9. Which of the following is correct way to declare string variable in Python? a. fruit = 'banana' b. fruit = \"banana\" c. fruit = banana d. fruit = (banana) 10. What will be the output for: name=\"Hello World\" print(type(name)) a. Hello World b. hello World c. <class 'str'> d. Str Answers 1-d, 2-a, 3-a, 4-b, 5-b, 6-a, 7-d, 8-b, 9-a&b, 10-c 1.11REFERENCES CU IDOL SELF LEARNING MATERIAL (SLM)

Text Books:  Allen B. Downey, “Think Python: How to Think likea Computer Scientist”, 2nd edition, Updated for Python 3, Shroff/O ‘Reilly Publishers, 2016  Michael Urban, Joel Murach, Mike Murach: Murach'sPython Programming; Dec, 2016 Reference Books:  Guido van Rossum and Fred L. Drake Jr, An Introduction to Python – Revised and updated for Python 3.2,  Jake VanderPlas, “Python Data Science Handbook”, O ‘Reilly Publishers, 2016. 26 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 2: INTRODUCTION TO PYTHON DATA STRUCTURES Structure 2.0. Learning Objectives 2.1. Lists 2.2. Tuples 2.3. Sets 2.4. Dictionaries 2.5. Summary 2.6. Keywords 2.7. Learning Activity 2.8. Unit End Questions 2.9. References 2.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the need of List, tuple and sets  Familiarize the concept of dictionaries  Compare list, tuples, sets and dictionaries 2.1 LISTS In Python, a list is a flexible data type. It is a sequence in which the elements are written as a list of comma-separated values (items) enclosed by square brackets. A list's distinguishing characteristic is that it can include elements of various data types. Syntax: List_variable = [val1, val2...] Example: L= [10,20,30,40] Accessing List Elements 27 CU IDOL SELF LEARNING MATERIAL (SLM)

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4. Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types; this will result in TypeError. Nested lists are accessed using nested indexing. Example my_list = ['p', 'r', 'o', 'b', 'e'] print(my_list[0]) print(my_list[2]) print(my_list[4]) n_list = [\"Happy\", [2, 0, 1, 5]] print(n_list[0][1]) print(n_list[1][3]) print(my_list[4.0]) Output p o e a 5 Traceback (most recent call last): File \"<string>\", line 21, in <module> TypeError: list indices must be integers or slices, not float 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. 28 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 2.1: Indexing in List Iterating Through a List Using a for loop we can iterate through each item in a list. for fruit in ['apple','banana','mango']: print (\"I like”, fruit) Basic List Operations Following table give the operations performed on lists: Operation Description Example Output len Returns length of the list len([1,2,3,4,5]) 5 + Joins two list [1,2,3,4,5] + [10,11] [1,2,3,4,5,10,11 ] * Repeats elements in the list “Hello”,”world”*2 [‘Hello’,’world’, Checks if the value is present in ‘a’ in ‘Hello’,’world’] in [‘a’,’e’,’i’,’o’,’u’ True the list ] True not in Checks if the value is not 3 not in [1,2,4,5,6] max present in the list 10 min N=[1,4,6,8,10,5] Returns maximum value in print(max(N)) 1 the list N=[1,4,6,8,10,5] 34 Returns the minimum print(min(N)) value in the list False N=[1,4,6,8,10,5] sum Adds the values in the list print(sum(N)) True [‘H’,’e’,’l’,’l’,’ Returns true if all the N=[1,0,6,8,10,5] all print(all(N)) o’] elements in the list are true N=[1,0,6,8,10,5] Returns true if any element print(any(N)) any L=list(“Hello”) in the list is true print(L) Converts tuple, string, set list or dictionary into a list 29 CU IDOL SELF LEARNING MATERIAL (SLM)

sorted Returns a new sorted list N=[1,0,6,8,10,5] [0,1,5,6,8,10] print(sorted(N)) Table 2.1 Basic List Operations List Slicing: Lists, like strings, can be sliced and concatenated. To view values in lists, use square brackets along with the index or indices to fetch the value stored at that index. Syntax: seq = ListName[start:stop:step] #accesses from start to stop-1 Example: [1,2,3,4,5,6,7,8,9,10] A=[1,2,3,4,5,6,7,8,9,10] print(A) # prints print(A[2:5]) # prints [3,4,5] print(A[ :5 ] #prints [1,2,3,4] Print(A[ 3: ] #prints[4,5,6,7,8,9,10] Print(A[ : ] #prints [1,2,3,4,5,6,7,8,9,10] print(A[::2]) # prints [1,3,5,7,9] print(A[1::3]) # prints [2,5,8] List Mutability: The list is a data structure that can be modified. This ensures that the components can be modified, included, or deleted. On the left side of an assignment operation, a slice operator may update single or multiple elements of a list. The append() method may be used to add new elements to the list. Example: prints [10,15,30,45] l= [10,15,30,45] print l # = l[1] 100 print l # prints [10,100,30,45] 30 CU IDOL SELF LEARNING MATERIAL (SLM)

List aliasing: When one list is assigned to another list using the assignment operator (=), then a new copy of the list is not made. Instead, assignment makes two variables point to the one list in memory. Example: #prints [1,2,3,4,5] list1= list1 list2= print(list2) [1,2,3,4,5] list2[2]=200 print (list1) # prints[1,2,200,4,5] Cloning Lists: If you want to modify a list and also keep a copy of the original list, then you should create a separate copy of the list (not just the reference). This process is called cloning. The slice operation is used to clone a list. Example: l1=[1,2,3,4,5,6,7,8,9,10] l2=l1.copy() print(l2) # prints [1,2,3,4,5,6,7,8,9,10] l3=l1[ :5] print(l3) #prints[1,2,3,4] List Methods: Operation Description Syntax Example Output append() Appends an element list.append(val) L=[10,20,30,40] [10,20,30,40,100] at the last L.append(100) to the list. print(L1) count() Counts the number of list.count(val) L=[10,20,30,20] 2 times an element print(L.count(20)) appears in the list. 31 CU IDOL SELF LEARNING MATERIAL (SLM)

index() Returns the lowest list.index(val) L=[10,20,30,20] 1 index of an element in print(L.index(20)) the list. insert() Inserts the value at list.insert(index,v L=[10,20,30,20] [10,100,20,30,20] the specified index in al) L.insert(1,100) the list print(L) pop() Removes the element list.pop(index) L=[10,20,30,20] [10,30,20] at the L.insert(1) print(L) specified index from the list remove() Removes or deletes list.remove(val) L=[10,20,30,20] [20,30,20] val from the list L.remove(10) print(L) reverse() Reverse the elements list.reverse() L=[10,20,30,20] [20,30,20,10] in the list. L.reverse() print(L) sort() Sorts the elements in list.sort() L=[10,20,30,20] [10,20,20,30] the list. L.sort() print(L) extend() Adds the elements in list.extend(list2) L=[10,20,30] [10,20,30,100,200] a list to the end of L1=[100,2000] another list L.extend(L1) print(L) Used to copy the L=[10,20,30,20] [10,20,30,20] content of list from L1=L.copy() copy() list1=list.copy() print(L1) one to another Finds the length of the len(list) L=[10,20,30,20] 4 len() print(len(L)) list 32 CU IDOL SELF LEARNING MATERIAL (SLM)

max() Gives the maximum max(list) L=[10,20,30,20] 30 min() element in the list min(list) print(max(L)) 10 [] Gives the minimum L=[10,20,30,20] Name Error element in the list print(min(L)) clear() Clears all the element list.clear() L=[10,20,30,20] in the list L.clear() print(L) del deletes the entire list del list L=[10,20,30,20] del L Table 2.2 List Functions in Python Python's for and in constructs are extremely useful especially when working with lists. The forvar in list statement is an easy way to access each element in a list (or any other sequence). For example, in the following code, the for loop is used to access each item in the list. Python program to print sum of elements in a List list1=[3,5,7,6,2,9] sum=0 fori in list1: sum +=i print sum Output: 32 Python program to print odd Numbers in a List 33 CU IDOL SELF LEARNING MATERIAL (SLM)

# list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list fornum in list1: # checking condition ifnum % 2 != 0: print(num, end = \" \") Output: 21 45 93 Program to find sum of odd and even numbers in a list NumList=[] #empty list evenSum=0 #declare and initialised variable evenSum to sum of even numbers oddSum=0 #declare and initialised variable oddSum to sum of odd numbers Number=int(input(\"Please enter the total number of list elements: \")) fori in range( Number): value=input(\"Please enter the value: \") NumList.append(value) for j in range(Number): if(NumList[j]%2==0): evenSum=evenSum+NumList[j] else: oddSum=oddSum+NumList[j] print(\"The sum of even numbers in the list= \",evenSum) print(\"The sum of odd numbers in the list= \",oddSum) 34 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: Please enter the total number of list elements: 6 Please enter the value: 12 Please enter the value: 21 Please enter the value: 23 Please enter the value: 32 Please enter the value: 34 Please enter the value: 43 The sum of even numbers in the list= 78 The sum of odd numbers in the list= 87 Exercise: Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. words = ['abc', 'xyz', 'aba', '1221'] ctr = 0 for word in words: if len(word) > 1 and word[0] == word[-1]: ctr += 1 print(“Result “,ctr) Exercise: Write a python program that takes a list and returns a new list that contains all the elements of the first list without any duplicates. 35 CU IDOL SELF LEARNING MATERIAL (SLM)

# all the elements of the first list minus duplicates. inpt_lst = [1,2,3,4,3,2,1] reslt_lst = [] for i in inpt_lst: if i not in reslt_lst: reslt_lst.append(i) print(“Result “, reslt_lst) Output Result [1,2,3,4] NESTED LISTS A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. Example L = ['A', ['BB', ['CCC', 'DDD'], 'EE', 'FF'], 'G', 'H'] Figure 2.2 Nested List LIST COMPREHENSIONS Python also supports computed lists called list comprehensions having the following syntax. List = [expression for variable in sequence] where, the expression is evaluated once, for every item in the sequence. 36 CU IDOL SELF LEARNING MATERIAL (SLM)

List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new lists where each element is the obtained by applying some operations to each member of another sequence or iterable. List comprehension is also used to create a subsequence of those elements that satisfy a certain condition. Example c= [i**3 for i in range (11)] print (c) Output: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] Example print ([(x, y) for x in [10,20,30] for y in [30,10,40] if x! = y]) Output: [(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)] 2.2 TUPLES Like lists, tuple is another data structure supported by Python. It is very similar to lists but differs in two things.  First, a tuple is a sequence of immutable objects. This means that while you can change the value of one or more items in a list, you cannot change the values in a tuple.  Second, tuples use parentheses to define its elements whereas lists use square brackets. Creating Tuple Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need to just put the different comma-separated values within a parenthesis as shown below. Tuple name = (val1, val2,) 37 CU IDOL SELF LEARNING MATERIAL (SLM)

wherever (or values) can be an integer, a floating number, a character, or a string. Example tuple1= (‘abcd’, 345 , 3.2, ‘python’, 3.14) print(tuple1) Output: (‘abcd’, 345, 3.2,’python’, 3.14) Accessing Values in a Tuple: Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0. You can even perform operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is used along with the index or indices to obtain value stored at that index. Example T = (1,2,3,4,5,6,7,8,9,10) print(“Tuple[ 3:6] =”,T[3:6]) print(“Tuple[ : 4] =”, T[ :4]) print(“Tuple[ 4 : ] =”, T[ 4 : ]) print(“Tuple[ : ] =”, T[ : ]) Output: Tuple[ 3:6] = (4,5,6) Tuple[ : 4] = (1,2,3,4) Tuple[ 4 : ] = (5,6,7,8,9,10) Tuple[ : ] = (1,2,3,4,5,6,7,8,9,10) Deleting Elements in Tuple: Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, we can create a new tuple that has all elements in our tuple except the ones we don't want (those we wanted to be deleted). 38 CU IDOL SELF LEARNING MATERIAL (SLM)

tup1 = ('C', 'C++', 'python', Tup1 = (1,2,3,4,5) Tup1 = (1,2,3,4,5) del(Tup1) 1997, 2000) del (Tup1[3]) print(Tup1) tup1[0] =’Java’ print (Tup1) Output: Output: Output: Traceback (most recent call Traceback (most recent call Traceback (most recent call last): last): last): File \"main.py\", line 2, in File \"main.py\", line 2, in File \"main.py\", line 3, in tup1[0] ='Java' del (Tup1[3]) print(Tup1) TypeError: 'tuple' object does TypeError: 'tuple' object does NameError : name ‘Tup1’ is not support item assignment not support item deletion notdefined Basic Tuple Operations: Operation Expression Output Len len(1,2,3,4,5) 5 concatenation (1,2,3) + (4,5,6) (1,2,3,4,5,6) Repetition (‘Good’) *3 (‘GoodGoodGood’) In 5 in (1,2,3,4,5,6,7) True False not in 5 not in (1,2,3,4,5,6,7) 13 max max(2,4,6,8,13,7) 2 min min(2,4,6,8,13,7) 1,2,3,4,5,6 Iteration for i in (1,2,3,4,5,6) False print(i) Comparison (‘H’,’e’,’l’,’l’,’o’) tuple T1=(1,2,3,4,5) (1,2,3,4,5) T2=(1,2,3,4,5) print(T1 >T2) Tuple(“Hello”) Tuple([1,2,3,4,5]) 39 CU IDOL SELF LEARNING MATERIAL (SLM)

Table 2.3 Basic List Operations Tuple Assignment: Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the assignment operator to be assigned values from a tuple given on the right side of the assignment operator. Each value is assigned to its respective variable. In case, an expression is specified on the right side of the assignment operator, first that expression is evaluated and then assignment is done. Example: a,b,c) = (1,2,3) print(a,b,c) Tup1=(100,200,300) (t1,t2,t3)= Tup1 print (t1,t2,t3) (a,b,c) = (2+5, 5/3+4, 9%6) print(a,b,c) (t1,t2,t3)=(1,2) print (t1,t2,t3) Output: 12 3 100 200 300 7 5.666667 3 Traceback (most recent call last) : File “<stdin>”, line 8 in (t1,t2,t3)=(1,2) Value Error : need more than 2 values to unpack Differences between lists and tuples:  Lists are enclosed in square brackets [] and their elements and size can be changed.  But tuples are enclosed in parentheses () and cannot be updated.  Tuples are immutable, so iterating through tuple is faster than with list.  Tuples can be thought of as read-only lists. 40 CU IDOL SELF LEARNING MATERIAL (SLM)

Advantages of Tuple over List:  Tuples are used to store values of different data types. Lists can however, store data of similar data types.  Since tuples are immutable, iterating through tuples is faster than iterating over a list. This means that a tuple performs better than a list.  Tuples can be used as key for a dictionary, but lists cannot be used as keys.  Tuples are best suited for storing data that is write-protected.  Tuples can be used in place of lists where the number of values is known and small.  If you are passing a tuple as an argument to a function, then the potential for unexpected behaviour due to aliasing gets reduced.  Multiple values from a function can be returned using a tuple.  Tuples are used to format strings. 2.3 SETS A set is a selection of objects that are not in any particular order. Any set element must be unique (no duplicates) and immutable (cannot be changed). A set, on the other hand, is mutable. We have the ability to add and delete objects from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc. Creating Python Sets A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set () function. It 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. 41 CU IDOL SELF LEARNING MATERIAL (SLM)

Example my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, \"Hello\", (1, 2, 3)} print(my_set) Output: {1, 2, 3} {1.0, (1, 2, 3), 'Hello'} Modifying a set: Sets may be modified. However, indexing has no sense because they are not ordered. Indexing or slicing cannot be used to view or modify a fixed variable. It is not supported by the Set data type. We will use the add () method to add a single element and the update () method to add several elements. The update () method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. Example y_set = {1, 3} print(my_set) # add an element my_set.add(2) print(my_set) # add multiple elements my_set.update([2, 3, 4]) print(my_set) my_set.update([4, 5], {1, 6, 8}) print(my_set) 42 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: {1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8} Removing elements from a set: A particular item can be removed from a set using the methods discard () and remove (). The only difference between the two is that the discard () function leaves a set unchanged if the element is not present in the set. On the other hand, the remove () function will raise an error in such a condition (if element is not present in the set). Example my_set = {1, 3, 4, 5, 6} print(my_set) my_set.discard(4) print(my_set) # remove an element my_set.remove(6) print(my_set) # discard an element my_set.discard(2) print(my_set) Output: 43 {1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} Python Set Operations Set Union: Union of A and B is a set of all elements from both sets. CU IDOL SELF LEARNING MATERIAL (SLM)

Union is performed using | operator. Same can be accomplished using the union () method. Example: # Set union method A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) Output: {1, 2, 3, 4, 5, 6, 7, 8} Set Intersection: Intersection of A and B is a set of elements that are available in both the sets. Intersection is performed using & operator. Same can be accomplished using the intersection () method. Example: # Intersection of sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A & B) Output: {4, 5} Set Difference: Difference of the set B from set A (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator. Same can be accomplished using the difference () method. 44 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: # Difference of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A - B) Output: {1, 2, 3} Set Symmetric Difference: Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection). Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric difference (). Example: A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A ^ B) Output: {1, 2, 3, 6, 7, 8} Set Methods Description Adds an element to the set Method Removes all elements from the set add() Returns a copy of the set clear() Returns the difference of two or more sets as a new set copy() Removes all elements of another set from this set difference() Removes an element from the set if it is a member. (Do difference_update() nothing if the element is not in set) discard() Returns the intersection of two sets as a new set Updates the set with the intersection of itself and another intersection() Returns True if two sets have a null intersection intersection_update() Returns True if another set contains this set isdisjoint() issubset() 45 CU IDOL SELF LEARNING MATERIAL (SLM)

issuperset() Returns True if this set contains another set pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty remove() Removes an element from the set. If the element is not a member, raises a KeyError symmetric_difference() Returns the symmetric difference of two sets as a new set symmetric_difference_update() Updates a set with the symmetric difference of itself and another union() Returns the union of sets in a new set update() Updates the set with the union of itself and others Table 2.4 Methods used with Sets Write a Python program to check if a specified element presents in a tuple of tuples. def check_in_tuples(colors, c): result = any(c in tu for tu in colors) return result colors = ( ('Red', 'White', 'Blue'), ('Green', 'Pink', 'Purple'), ('Orange', 'Yellow', 'Lime'), ) print(\"Original list:\") print(colors) c1 = 'White' 46 CU IDOL SELF LEARNING MATERIAL (SLM)

print(\"Check if\",c1,\"present in said tuple of tuples!\") print(check_in_tuples(colors, c1)) c1 = 'White' print(\"Check if\",c1,\"present in said tuple of tuples!\") print(check_in_tuples(colors, c1)) c1 = 'Olive' print(\"Check if\",c1,\"present in said tuple of tuples!\") print(check_in_tuples(colors, c1)) Output Original list: (('Red', 'White', 'Blue'), ('Green', 'Pink', 'Purple'), ('Orange', 'Yellow', 'Lime')) Check if White present in said tuple of tuples! True Check if White present in said tuple of tuples! True Check if Olive present in said tuple of tuples! False 2.4 DICTIONARIES A dictionary is a type of data structure that stores values as a pair of key and value. A colon (:) separates each key from its value, and commas distinguish consecutive objects. Curly brackets {}surround the complete items in a dictionary The syntax for defining a dictionary is dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….} 47 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: Dict = { ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’} print(Dict) Output: { ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’} Accessing Elements from Dictionary: While other data types use indexing to reach variables, a dictionary uses keys. Keys can be used using either square brackets [] or the get() form. If we use square brackets [], we get a Key Error if a key is not included in the dictionary. On the other hand, the get () method returns None if the key is not found. Example: my_dict = {'name': 'Jack', 'age': 26} print(my_dict['name']) print(my_dict.get('age')) print(my_dict.get('address')) print(my_dict['address']) Output: Jack 26 None Traceback (most recent call last): File \"<string>\", line 15, in <module> print(my_dict['address']) KeyError: 'address' Changing and Adding Dictionary elements: Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator. If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary. 48 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: # Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 print(my_dict) # add item my_dict['address'] = 'Downtown' print(my_dict) Output: {'name': 'Jack', 'age': 27} {'name': 'Jack', 'age': 27, 'address': 'Downtown'} Removing elements from Dictionary: We can remove a particular item in a dictionary by using the pop () method. This method removes an item with the provided key and returns the value. The pop item () method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear () method. We can also use the del keyword to remove individual items or the entire dictionary itself. Example: squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value print(squares.pop(4)) print(squares) # remove an arbitrary item, return (key,value) print(squares.popitem()) print(squares) # remove all items squares.clear() print(squares) # delete the dictionary itself del squares 49 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: 16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Dictionary Methods Method Description clear() Removes all items from the dictionary. copy() Returns a shallow copy of the dictionary. fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None). get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None). items() Return a new object of the dictionary's items in (key, value) format. keys() Returns a new object of the dictionary's keys. pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys. values() Returns a new object of the dictionary's values Table 2.5 Dictionary Method in Python Exercise: Write a Python program to combine two dictionary adding values for common keys. 50 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook