Python
Python - Sets
Python Sets:
A set is created by placing all the items (elements) inside curly braces {}, separated by a 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.
- Sets are an unordered collection of unique elements. We can construct them by using the set() function.
- Sets cannot contain duplicates.
- Sets are mutable like lists.
- You can create a non-empty set with curly braces by specifying elements separated by a comma.
- Set items can be of any data type.
- Sets can be any data type.
set1 = ("apple", "banana", "cherry")
set2 = {1, 5, 7, 9.0, 3.9,'abc','cde'}
set3 = (1,2,3,4,5)
Empty_set = set()Python Sets Functions and methods:
add()
- add( ) - the method adds an element to the set.
- This method takes the element to be added as an argument to the given set.
Example:set_1 = set()set_1.add('hi!')print(set_1)Result:{'hi!'}
update()
- update( ) - the method helps to add multiple elements to a set.
Example:set_2 = {5,7,9,3}set_2.update([2, 3, 4])print(set_2)Result:{2, 3, 4, 5, 7, 9}
remove()
- Use remove( ) to remove an item/element from the set.
- By default remove( ), removes the specified element from the set.
- remove( ), takes the element as an argument.
Example:set_3 = {1,6,34,12,32,46,'a','g','h'}set_3.remove(46)print(set_3)Results:{1, 12, 32, 34, 6, 'a', 'g', 'h'}
dict()
- We can also create dictionary objects from a sequence of items that pair. This can be done using the - dict( ) method.
- dict( ), the function takes the list of paired elements as an argument in the list of tuples.
Example:state_city = [ ( 'Andhrapradesh',' Visakhapatnam'),('Karnataka','Bangaluru'),('Telangana','Hyderabad')]state_city = dict(state_city)print(state_city)Result:{'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru', 'Telangana': 'Hyderabad'}
pop()
pop( )- the method removes and returns an element from a dictionary having the given key.
This method takes two arguments/parameters (i) key - key which is to be searched for removal, (ii) default - value which is to be returned when the key is not in the dictionary.
Example:state_city = {'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru', 'Telangana': 'Hyderabad'}state_city.pop("Telangana")print(state_city)Result:{'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru'}
No comments:
Post a Comment