Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Notes

The document provides an overview of Python programming, covering its features, history, and basic concepts such as variables, data types, and operators. It explains the differences between Python and other programming languages, the importance of indentation, and the types of errors encountered in programming. Additionally, it discusses lists and their mutability, along with various methods for manipulating them.

Uploaded by

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

Python Notes

The document provides an overview of Python programming, covering its features, history, and basic concepts such as variables, data types, and operators. It explains the differences between Python and other programming languages, the importance of indentation, and the types of errors encountered in programming. Additionally, it discusses lists and their mutability, along with various methods for manipulating them.

Uploaded by

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

Python Programming

FE0_SEC_PYP_T202
Module 1
Basics of Python:
By
Ms. Harshal P G
Asst. Professor, SFIT
MODULE 1

Basics of Python:
1.1 Introduction: Features of Python, Comparison of Python with C/C++

1.2 Python building blocks: Identifiers, Keywords, Indention, Variables


and Comments, Basic data types, Operators, Input-output, string

1.3 Sequence data types: List, tuple, set and dictionary


• What is Python?

Python is an example of a high-level language; other


high-level languages you might have heard of are C++,
PHP, and Java.

• Multi-purpose (Web, GUI, Scripting, etc.)


Object Oriented

• Interpreted

• Focus on readability and productivity


History of Python:
• Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherland

• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.

• Python Syntax compared to other programming languages


• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.
Features of python:

• Easy-to-learn: Python has few keywords, simple structure, and a clearly


defined syntax. This allows a student to pick up the language quickly.

• Easy-to-read: Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain: Python's source code is fairly easy-to-maintain.

• A broad standard library: Python's bulk of the library is very portable and
cross platform compatible on UNIX, Windows, and Macintosh.

• Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.

• Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.

• Databases: Python provides interfaces to all major commercial databases.

• GUI Programming: Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.

• Scalable: Python provides a better structure and support for large programs than shell
scripting.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.
• Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
Creating a Comment
• Comments starts with a #, and Python will ignore them:

Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Interpreter VS Compiler
• Two kinds of applications process high-level languages into low-level languages:
interpreters and compilers.

• An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and
performing computations.

• A compiler reads the program and translates it into a low-level program, which can then be
run.
• In this case, the high-level program is called the source code, and the translated program
is called the object code or the executable. Once a program is compiled, you can execute
it repeatedly without further translation.
• Many modern languages use both processes. They are first compiled into a
lower level language, called byte code, and then interpreted by a program
called a virtual machine. Python uses both processes, but because of the way
programmers interact with it, it is usually considered an interpreted language

• There are two ways to use the Python interpreter: shell mode and script mode.

• In shell mode, you type Python statements into the Python shell and the
interpreter immediately prints the result.
• Running Python program:

There are three different ways to start Python-

(1) Interactive Interpreter


You can start Python from Unix, DOS, or any other system that provides you a
command line interpreter or shell window.

(2) Script from the Command-line(cmd)

(3) Integrated Development Environment


What is Debugging ?
• Programming is a complex process, and because it is done by human beings, programs often
contain errors. For whimsical reasons, programming errors are called bugs and the process of
tracking them down and correcting them is called debugging.
• Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors. It is useful to distinguish between them in order to track them down more quickly
• Syntax errors
• Python can only execute a program if the program is syntactically correct; otherwise, the
process fails and returns an error message. Syntax refers to the structure of a program and
the rules about that structure. For example, in English, a sentence must begin with a capital
letter and end with a period. this sentence contains a syntax error.
• So does this one For most readers, a few syntax errors are not a significant problem, which is
why we can read the poetry of e. e. cummings without spewing error messages. Python is not
so forgiving. If there is a single syntax error anywhere in your program, Python will print an
error message and quit, and you will not be able to run your program.
• During the first few weeks of your programming career, you will probably spend a lot of time
tracking down syntax errors. As you gain experience, though, you will make fewer syntax
errors and find them faster.
Runtime errors
• The second type of error is a runtime error, so called because the error does not appear until you
run the program. These errors are also called exceptions because they usually indicate that
something exceptional (and bad) has happened. Runtime errors are rare in the simple programs

Semantic errors
• The third type of error is the semantic error. If there is a semantic error in your program, it will
run successfully, in the sense that the computer will not generate any error messages, but it will
not do the right thing. It will do something else.
• Specifically, it will do what you told it to do.
• The problem is that the program you wrote is not the program you wanted to write. The meaning
of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it
requires you to work backward by looking at the output of the program and trying to figure out
what it is doing.
• Formal and Natural Languages:
• Natural languages are the languages that people speak, such as
English, Spanish, and French. They were not designed by people
(although people try to impose some order on them); they evolved
naturally.
• Formal languages are languages that are designed by people for
specific applications. For example, the notation that mathematicians use
is a formal language that is particularly good at denoting relationships
among numbers and symbols.

• Programming languages are formal languages that have been


designed to express computations.
Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Keywords define the language’s rules and structure, and they cannot be used as variable names.
Multi-Words Variable Names
• Variable names with more than one word can be difficult to read.
• There are several techniques you can use to make them more readable:
• Camel Case
• Each word, except the first, starts with a capital letter:
• myVariableName = "John“
• Pascal Case
• Each word starts with a capital letter:
• MyVariableName = "John"
• Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John"
• Variables do not need to be declared with any particular type, and
can even change type after they have been set.

• Casting
If you want to specify the data type of a variable, this can be done
with casting.
Get the Type
• You can get the data type of a variable with the type() function.

Python Datatypes
1.Numeric – int , float, complex
2. String
It can be declared either by using single or double quotes:
• print("Hello")
print('Hello')
Multiline Strings
• You can assign a multiline string to a variable by using three double or single quotes:
• a = """Lorem ipsum dolor sit amet, a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit, consectetur adipiscing elit,
ut labore et dolore magna aliqua.""" ut labore et dolore magna aliqua.'''
b = "Hello, World!“
1. Accessing elements
b[0]
b[-1]
b[-6]
2. Slicing
print(b[2:5])
print(b[:5])
print(b[2:])
3. Replace String
print(b.replace("H", "J"))
4. Split String
print(b.split(",")) # returns ['Hello', ' World!']
5. String Concatenation
• a = "Hello"
b = "World"
c=a+b
print(c) # HelloWorld
• c=a+""+b
print(c) # Hello World
6. String Length
Len(b)
7. Miscellaneous
b.capitalize() b.count(‘o’) b.find(‘Wo’)

b.upper() b.lower() b.isalpha()

b.isalnum b.isspace b.startswith(“hello”)

b.endswith(“!”) b*3
3. Boolean
• Booleans represent one of two values: True or False.
• print(10 > 9) #True
print(10 == 9) #False
print(10 < 9) #False
• x = "Hello"
y = 15
print(bool(x)) #True
print(bool(y)) #True
• The following will return False:
• bool(False)
• bool(None)
• bool(0)
• bool("")
Operators in Python
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Assignment
Comparison Bitwise
Logical

Membership
Identity
Lists :
• A list is an ordered set of values, where each value is identified by an index.
• The values that make up a list are called its elements .
• Lists are similar to strings, which are ordered sets of characters, except that the
elements of a list can have any type.
• Lists and strings—and other things that behave like ordered sets—are called
sequences .
• The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
• Important thing about a list is that the items in a list need not be of the
same type.
• There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
• [10, 20, 30, 40] ["spam", "bungee", "swallow"] [10, “spam”,30,40,”swallow”]
• A list within another list is said to be nested .
• Finally, there is a special list that contains no elements. It is called the empty list,
and is denoted []. Like numeric 0 values and the empty string, the empty list is
false in a boolean expression
Lists are mutable :
• Unlike strings lists are mutable , which means we can change their elements.
• Using the bracket operator on the left side of an assignment, we can update one of
the elements:
>>> fruit = ["banana", "apple", “berry"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
[’pear’, ’apple’, ’orange’]

An assignment to an element of a list is called item assignment.


• Item assignment does not work for strings:
>>> my_string = "TEST"
>>> my_string[2] = "X"
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: ’str’ object does not support item assignment

• but it does for lists:


>>> my_list = ["T", "E", "S", "T"]
>>> my_list[2] = "X"
>>> my_list
[’T’, ’E’, ’X’, ’T’]
• With the slice operator we can update several elements
at once:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = ["x", "y"]
>>> print a_list
[’a’, ’x’, ’y’, ’d’, ’e’, ’f’]

• We can also remove elements from a list by assigning


the empty list to them:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = []
>>>print (a_list )
[’a’, ’d’, ’e’, ’f’]
• And we can add elements to a list by squeezing
them into an empty slice at the desired location:
>>> a_list = ["a", "d", "f"]
>>> a_list[1:1] = ["b", "c"]
>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’f’]

>>> a_list[4:4] = ["e"]


>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
• Deleting elements from List :
>>>list = ['physics', 'chemistry', 1997, 2000]
>>>del list[2]
>>>print ("After deleting value at index 2 : ", list)

After deleting value at index 2 : ['physics', 'chemistry', 2000]


Concatenation Membership operator
>>>lst1=[12, 34, 56] >>>lst1=[12, 34, 56, 78, 90]
>>>lst2=[78, 90] >>>56 in lst1
>>>print(lst1+lst2) >>>12 not in lst1
#Output
• #Output True
[12, 34, 56, 78, 90] False

Repetition Len()
>>>lst1=[12, 34, 56] >>>lst1=[12, 34, 56]
>>>print( lst1*3) >>>print(len(lst1))
• #Output
#Output
[12, 34, 56, 12, 34, 56, 12, 34, 56] 3
List list() Method : List sort() Method :
• The list()method takes sequence types and
converts them to lists. This is used to convert
a given tuple into list. >>>list1 = ['physics', 'Biology', 'chemistry',
• Note: Tuple are very similar to lists with only 'maths']
difference that element values of a tuple can
not be changed and tuple elements are put >>>list1.sort()
between parentheses instead of square
bracket. This function also converts >>>print ("list now : ", list1)
characters in a string into a list. >>>list now : ['Biology', 'chemistry',
'maths', 'physics']
>>>aTuple = (123, 'C++', 'Java', 'Python')
>>>list1 = list(aTuple)
>>>print ("List elements : ", list1) • Note: this method sorts the list as
alphabetically , incase of numbers it will
sort according to its value
>>>str="Hello World"
>>>list2=list(str)
>>>print ("List elements : ", list2)
List count()Method List append() Method :
• This method returns count of how • The append() method appends a
many times obj occurs in list. passed obj into the existing list.
>>>aList = [123, 'xyz', 'zara', 'abc', 123]; >>>list1 = ['C++', 'Java', 'Python']
>>>print ("Count for 123 : ", >>>list1.append('C#')
aList.count(123)) >>>print ("updated list : ", list1)
>>>print ("Count for zara : ",
aList.count('zara')) • updated list :['C++', 'Java',
'Python‘, ’C#’]
• Count for 123 : 2
• Count for zara : 1 • NOTE: append method used to add
element in list at last position
List index() Method List extend()Method
• The index() method returns the lowest • The extend() method appends the contents
index in list that obj appears. of seq to list.

>>>list1 = ['physics', 'chemistry', 'maths'] >>>list1 = ['physics', 'chemistry', 'maths']


>>>print ('Index of chemistry', >>>list2=list(range(5)) #creates list of numbers
list1.index('chemistry')) between 0-4
>>>print ('Index of C#', list1.index('C#')) >>>list1.extend('Extended List :', list2)
>>>print(list1)
Index of chemistry 1
Not found Extended List : ['physics', 'chemistry', 'maths‘, 0,
1, 2, 3, 4]
List pop() Method : List insert() Method :
• The pop() method removes and • The insert() method inserts object obj
returns last object or obj from the list. into list at offset index.
>>>list1 = ['physics', 'chemistry', 'maths']
>>>list1 = ['physics', 'Biology', 'chemistry', >>>list1.insert(1, 'Biology')
'maths']
>>>print ('Final list : ', list1)
>>>list1.pop()
>>>print ("list given : ", list1)
>>> list1.pop(1) • Final list : ['physics', 'Biology', 'chemistry',
>>>print ("list now : ", list1) 'maths']

• list given: ['physics', 'Biology',


'chemistry']
• list now: ['physics', 'chemistry']
List remove()Method : List reverse()Method
This is the object to be removed from the The reverse() method reverses objects of list
list. in place.

>>>list1 = ['physics', 'Biology', 'chemistry', >>>list1 = ['physics', 'Biology', 'chemistry',


'maths'] 'maths']
>>>list1.remove('Biology') >>>list1.reverse()
>>>print ("list now : ", list1) >>>print ("list now : ", list1)
>>> list1.remove('maths')
>>>print ("list now : ", list1) • list now :['maths', 'chemistry', 'Biology',
'physics']
• list now : ['physics', 'chemistry', 'maths']
• list now: ['physics', 'chemistry']
List cmp() method : (not there list1 = [1, 2, 4, 10]
in python3
list1 = [1, 2, 4, 3] list2 = [1, 2, 4, 'a']
list2 = [1, 2, 5, 8] list3 = ['a', 'b', 'c']
list3 = [1, 2, 5, 8, 10]
list4 = [1, 2, 4, 3]
list4 = ['a', 'c', 'b']
list5 = [7, 2, 5, 8]
print (cmp(list2, list1)) #1
print (cmp(list2, list1)) #1
print (cmp(list2, list3)) #-1 print (cmp(list2, list3)) #-1
print (cmp(list4, list1)) #0 print (cmp(list3, list4)) #-1
print (cmp(list3, list5)) #-1
Tuples
• tuple is a sequence of immutable Python objects.
• Tuples are sequences, just like lists.
• The main difference between the tuples and the lists is that the tuples cannot be
changed unlike lists. Tuples use parentheses, whereas lists use square brackets .
• Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these
comma-separated values between parentheses also.
For example-
• tup1 = ('physics', 'chemistry', 1997, 2000)
• tup2 = (1, 2, 3, 4, 5 )
• tup3 = "a", "b", "c", "d"
• The empty tuple is written as two parentheses containing nothing.
• tup1 = ();
• To write a tuple containing a single value you have to include a comma, even though there is only one
value.
• tup1 = (50,) Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Accessing values in Tuples : tuple()Method
• To access values in tuple, use • It converts a list of items into
the square brackets for slicing tuples.
along with the index or indices to >>>list1= ['maths', 'che', 'phy',
obtain the value available at that 'bio']
index. >>>tuple1=tuple(list1)
>>>tup1 = ('physics', 'chemistry', 1997, 2000) >>>print ("tuple elements : ",
>>>tup2 = (1, 2, 3, 4, 5, 6, 7 ) tuple1)
>>>print ("tup1[0]: ", tup1[0])
>>>print ("tup2[1:5]: ", tup2[1:5]) • tuple elements : ('maths', 'che',
'phy', 'bio')
tup1[0] : physics
tup2[1:5] : [2, 3, 4, 5]
Tuple Assignment :
• Once in a while, it is useful to perform multiple assignments in a single statement
and this can be done with tuple assignment :
>>> a,b = 3,4
>>> print(a) gives 3
>>> print (b) gives 4
>>> a,b,c = (1,2,3),5,6
>>> print (a) gives(1, 2, 3)
>>> print (b) gives 5
>>> print (c) gives 6

• The left side is a tuple of variables; the right side is a tuple of values. Each value is
assigned to its respective variable. This feature makes tuple assignment quite
versatile. Naturally, the number of variables on the left and the number of values
on the right have to be the same:
• Such statements can be useful shorthand for multiple assignment statements, but
care should be taken that it doesn’t make the code more difficult to read.
• One example of tuple assignment that improves readibility is when we want to
swap the values of two variables. With conventional assignment statements, we
have to use a temporary variable. For example, to swap a and b.
Dictionary
• Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this:
{ }.
• Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.

Accessing Values in a dictionary :


• To access dictionary elements, you can use the familiar square brackets along with the key to obtain its
value. Following is a simple example.
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>print ("dict['Name']: ", dict['Name'])
>>>print ("dict['Age']: ", dict['Age'])

• dict['Name']: Zara
• dict['Age']: 7
• Properties of Dictionary keys :
• Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys-
• A. More than one entry per key is not allowed. This means no
duplicate key is allowed. When duplicate keys are encountered during assignment,
the last assignment wins.
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
>>>print ("dict['Name']: ", dict['Name'])
o/p
• dict['Name']: Manni
• B. Keys must be immutable. This means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
>>>dict = {['Name']: 'Zara', 'Age': 7}
>>>print ("dict['Name']: ", dict['Name'])
o/p
• TypeError: list objects are unhashable
Operations in Dictionary :
• The del statement removes a key-value pair from a dictionary.
>>>inventory={’oranges’: 525, ’apples’: 430, ’pears’: 560,
’bananas’: 312}
>>> del inventory["pears"]
>>> print inventory
• {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
• Or if we’re expecting more pears soon, we might just change
the value associated with pears:
>>> inventory["pears"] = 0
>>> print inventory
• {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
• The len function also works on dictionaries; it returns the
number of key-value pairs:
>>> len(inventory) gives 4
Dictionary copy() Method Dictionary get() Method
• This method returns a shallow • This method returns a value for
copy of the dictionary. the given key. If the key is not
>>>dict1 = {'Name': 'Manni', available, then returns default
'Age': 7, 'Class': 'First'} value as None.
>>>dict2 = dict1.copy() >>>dict = {'Name': 'Zara', 'Age': 27}
>>>print ("New Dictionary : >>>print ("Value : " ,dict.get('Age'))
",dict2) >>>print (“Value : " , dict.get('Sex', "NA"))

• New dictionary : {'Name': Value : 27


'Manni', 'Age': 7, 'Class':'First'} Value : NA
Dictionary items() Method Dictionary update() Method
• The method returns a list • The method adds dictionary
of dict's (key, value) tuple dict2's key-values pairs in to dict.
This function does not return
pairs.
anything.
>>>dict = {'Name': 'Zara', 'Age': 7} >>>dict = {'Name': 'Zara', 'Age':
>>>print ("Value : " ,dict.items()) 7}
>>>dict2 = {‘Gender': 'female' }
>>>dict.update(dict2)
>>>print ("updated dict : ", dict)
• Value : dict_items([('Sex',
'female'), ('Age', 7), ('Name',
'Zara')])
updated dict : = {'Name': 'Zara',
'Age': 7, ‘Gender': 'female' }
Dictionary keys() Method : Dictionary values()Method

• The method returns a list of all • The method returns a list of


the available keys in the all the values available in a
dictionary. given dictionary.
>>>dict = {'Sex': 'female',
>>>dict = {'Name': 'Zara', 'Age': 7} 'Age': 7, 'Name': 'Zara'}
>>>print ("Values : ",
>>>print ("Value : " , dict.keys())
list(dict.values()))

• Values : ['female', 7, 'Zara']


• Value : dict_keys(['Name', 'Age'])
Set
It is used to store a collection of items with the following properties.
• No duplicate elements. If try to insert the same item again, it
overwrites previous one.
• An unordered collection. When we access all items, they are
accessed without any specific order and we cannot access items
using indexe as we do in lists.
• Internally use hashing that makes set efficient for search, insert
and delete operations. It gives a major advantage over a list for
problems with these operations.
• We can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.
thisset = {"apple", "banana", "cherry", "apple"} output
print(thisset) #{'banana', 'cherry', 'apple'} i.e no duplicate items apple
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
banana
thisset = {"apple", "banana", "cherry", True, 1, 2} Cherry
print(thisset) #{True, 2, 'banana', 'cherry', 'apple'}
print(len(thisset)) #5 True
print(type(thisset)) #<class 'set'> False
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

thisset = {"apple", "banana", "cherry"}


for x in thisset: {'apple', 'banana', 'cherry', 'orange'}
print(x)
print("banana" in thisset)
{'apple', 'banana', 'cherry', 'orange',
'pineapple', 'mango', 'papaya'}
print("banana" not in thisset)
print(thisset.add("orange")) {'apple', 'banana', 'cherry', 'orange',
tropical = {"pineapple", "mango", "papaya"} 'pineapple', 'mango', 'papaya', 'kiwi'}
Print(thisset.update(tropical))
mylist = ["kiwi", "orange"] {'apple', 'cherry', 'orange', 'pineapple',
print(thisset.update(mylist)) 'mango', 'papaya', 'kiwi'}
print(thisset.remove("banana")) or print(thisset.discard("banana"))
thisset = {"apple", "banana", "cherry"} • Output
print(thisset.pop()) banana
Banana #output {'apple', 'cherry'}
x = thisset.pop() set()
print(x)
print(thisset)
thisset.clear()
print(thisset)
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset) #this will raise an error
because the set no longer exists
set1 = {"a", "b", "c"} • Output:
set2 = {1, 2, 3}
set3 = {"John", "Elena"} {1, 'c‘, ’John’, 'a', 3,’Elena’, 'b', 2}
set4 = set1.union(set2,set3) or set1 | set2 |set3 -----------------------------------------------------
print(set4) {'apple'}
---------------------------------------------------------------- {'banana', 'cherry'}
set1 = {"apple", "banana", "cherry"} {'google', 'banana', 'microsoft', 'cherry'}
set2 = {"google", "microsoft", "apple"}
set3 = set1.intersection(set2) or set1 & set2
print(set3)
set4 = set1.difference(set2) or set1 - set2
print(set4)
set5 = set1.symmetric_difference(set2)
print(set5) or set1 ^ set2

You might also like