Q:

write a python program to explain Set, Union, Intersection, Difference, and Symmetric Difference

0

write a python program to explain Set, Union, Intersection, Difference, and Symmetric Difference

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

List is the most used data type in Python. A list can contain the same type of

items. Alternatively, a list can also contain different types of items. A list is

an ordered and indexable sequence.

list1=[34,2,1,22]
list2=[5,2,3,3]
print(list1+list2) #output: list1=[34,2,1,22]

 

List vs Tuple in python

Lists and tuples have the following differences:

• In lists, items are enclosed within square brackets [], whereas in tuples,

items are enclosed within parentheses ().

• Lists are mutable whereas Tuples are immutable. Tuples are read only lists.

Once the items are stored, the tuple cannot be modified.

Example for creating tuple in python:

third=(7, “eight”,9, 10.0)

 

sets in python

Union, Intersection, Difference and Symmetric Difference are some operations

which are performed on sets.

Union: Union operation performed on two sets returns all the elements from both

the sets. It is performed by using & operator.

Intersection: Intersection operation performed on two sets returns all the element

which are common or in both the sets. It is performed by using | operator.

Difference: Difference operation performed on two sets set1 and set2 returns the

elements which are present on set1 but not in set2. It is performed by using –

operator.

Symmetric Difference: Symmetric Difference operation performed on two sets

returns the element which are present in either set1 or set2 but not in both. It is

performed by using ^ operator.

examples of sets in python :

set1 = set([1, 2, 4, 1, 2, 8, 5, 4])
set2 = set([1, 9, 3, 2, 5])
print(set1) #Printing set
#set([8, 1, 2, 4, 5]) #Output
print(set2)

intersection = set1 & set2 #intersection of set1 and set2
print(intersection)

union = set1 | set2 # Union of set1 and set2
print(union) #Output set([1, 2, 3, 4, 5, 8, 9]) 

difference = set1 - set2 # Difference of set1 and set2
print(difference) #Output set([8, 4])

symm_diff = set1 ^ set2 # Symmetric difference of set1 and
print(symm_diff)  #Output set([3, 4, 8, 9])

 

 

Dictionary in python

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

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

Example: Create and print a dictionary:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now