Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically typed language; we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.





Ex. a = 5  





Python interpreter automatically interpret variables a as an integer type. For this Python provides us the type() function, which returns the type of the variable.





Python data types are divided in two categories, mutable data types and immutable data types.





Immutable Data types in Python
1. Numeric
2. String
3. Tuple





Mutable Data types in Python
1. List
2. Dictionary
3. Set





 





Standard data types





Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.





  1. Numbers
  2. Sequence Type
  3. Boolean
  4. Set
  5. Dictionary




Python Data Types




1.    Numbers





Number stores numeric values.





The integer, float, and complex values belong to a Python Numbers data-type.





Python provides the type() function to know the data-type of the variable.





Similarly, the isinstance() function is used to check an object belongs to a particular class.





Python creates Number objects when a number is assigned to a variable.





For example;





  1. a = 5  
  2. print("The type of a", type(a))    
  3. b = 40.5  
  4. print("The type of b", type(b))  
  5. c = 1+3j  
  6. print("The type of c", type(c))  
  7. print(" c is a complex number", isinstance(1+3j,complex))  




Output:





The type of a <class 'int'>




The type of b <class 'float'>




The type of c <class 'complex'>




c is complex number: True




Python supports three types of numeric data.





  1. Int - Integer value can be any length and without decimal values such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer.




  1. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate up to 15 decimal points. there is no need to specify the data type in Python. It is automatically inferred based on the value we are assigning to a variable. 




cnum = 3 + 4j





print(cnum)





print("Data Type of variable cnum is", type(cnum))





  • complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts. Numbers with real and imaginary parts are known as complex numbers. The complex numbers like 2.14j, 2.0 + 2.3j, etc.




  1. Long – Long data type is deprecated in Python 3 because there is no need for it, since the integer has no upper limit, there is no point in having a data type that allows larger upper limit than integers.




5.      Binary, Octal and Hexadecimal numbers -





In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number





# integer equivalent of binary number 101




num = 0b101




print(num)




 




# integer equivalent of Octal number 32




num2 = 0o32




print(num2)




 




# integer equivalent of Hexadecimal number FF




num3 = 0xFF




print(num3)




  output:- 5





            26





            255





2.     Sequence Type





 





String ’A’





The string can be defined as a bit of text (sequence of characters) represented in the quotation marks.





In Python, we can use single, double, or triple quotes to define a string.





For String handling Python provides built-in functions and operators to perform operations in the string.





The operator + is used to concatenate two strings:-





Ex. "hello"+" python" returns "hello python".





The operator * is known as a repetition operator.





Ex.  "Python" *2 returns 'Python Python'.





The following example illustrates the string in Python.





Example - 1





  1. str = "string using double quotes"  
  2. print(str)  
  3. s = '''''A multiline 
  4. string'''  
  5. print(s)  




Output:





string using double quotes




A multiline




string




Consider the following example of string handling.





Example - 2





  1. str1 = 'hello SJKPGM' #string str1    
  2. str2 = ' how are you' #string str2    
  3. print (str1[0:2]) #printing first two character using slice operator    
  4. print (str1[4]) #printing 4th character of the string    
  5. print (str1*2) #printing the string twice    
  6. print (str1 + str2) #printing the concatenation of str1 and str2    




Output:





he




o




hello SJKPGM hello SJKPGM




hello SJKPGM  how are you




 




# lets see the ways to create strings in Python




str = 'HELLO'




print(str)




 




str2 = "SJKPGM"




print(str2)




 




# multi-line string




str3 = """Welcome to 




   sjkpgm.in"""




print(str3)




 




str4 = '''This is a tech 




   blog'''




print(str4)




Output:





HELLO




SJKPGM




Welcome to 




   Sjkpgm.in




This is a tech 




   blog




A string is an array of characters, for this we use the indexes to access the characters.





Just like arrays, the indexes start from 0 to the length-1.





Index Error display if you try to access the character which is not in the range.





For example,
if a string length is 5 and you want to access the 6th char. then you will get TypeError .





str = "abcde"




 




# displaying whole string




print(str)




 




# displaying first character of string




print(str[0])




 




# displaying third character of string




print(str[2])




 




# displaying the last character of the string




print(str[-1])




 




# displaying the second last char of string




print(str[-2])




Output:





abcde




a




c




e




d




 





Python String Operations





1. Getting a substring in Python – Slicing operation





We can slice a string to get a substring out of it.





examples of slicing:-





 




str = "abcdefghijklm"




 




# displaying whole string




print("The original string is: ", str)




 




# slicing 10th to the last character




print("str[9:]: ", str[9:])




 




# slicing 3rd to 6th character




print("str[2:6]: ", str[2:6])




 




# slicing from start to the 9th character




print("str[:9]: ", str[:9])




 




# slicing from 10th to second last character




print("str[9:-1]: ", str[9:-1])




Output:





The original string is:  abcdefghijklm




str[9:]:  jklm 




str[2:6]:  cdef 




str[:9]:  abcdefghi




str[9:-1]:  jkl




 





2. Concatenation of strings in Python





The + operator is used for string concatenation in Python.





example:





str1 = "One"




str2 = "Two"




str3 = "Three"




 




# Concatenation of three strings




print(str1 + str2 + str3)




Output:





OneTwoThree




Note: if you try to use this between string and number then it will throw TypeError.





For example:





s = "one"




n = 2




print(s+n)




Output:





TypeError: must be str, not int




3. Repetition of string – Replication operator





We can use * operator to repeat a string by specified number of times.





str = "ABC"




 




# repeating the string str by 3 times




print(str*3)




Output:





ABCABCABC




 





4. Python Membership Operators in Strings





In:- This check whether a string is present in another string or not. It returns true if the entire string is found else it returns false.
not in: It works just opposite to what “in” operator does. It returns true if the string is not found in the specified string else it returns false.





str = "Welcome to sjkpgm.in"




str2 = "Welcome"




str3 = "Chaitanya"




str4 = "XYZ"




 




# str2 is in str? True




print(str2 in str)




 




# str3 is in str? False




print(str3 in str)




 




# str4 not in str? True




print(str4 not in str)




Output:





True




False




True




 





5. Python – Relational Operators on Strings





The relational operators works on strings based on the ASCII values of characters.
The ASCII value of a is 97, b is 98 and so on.
The ASCII value of A is 65, B is 66 and so on.





str = "ABC"




str2 = "aBC"




str3 = "XYZ"




str4 = "XYz"




 




# ASCII value of str2 is > str? True




print(str2 > str)




 




# ASCII value of str3 is > str4? False




print(str3 > str4)




Output:





True




False




 





List





Python Lists are similar to arrays in C. list can contain data of different types. The data stored in the list are separated with a comma (,) and enclosed within square brackets [].





We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with the list in the same as the strings.





List is a compound data type which means you can have different-2 data types under a list, for example we can have integer, float and string items in a same list.





Consider the following example.





list1  = [1, "hi", "Python", 2]    





#Checking type of given list  





print(type(list1))  





  Output:





[1, 'hi', 'Python', 2]




#Printing the list1  





print (list1)  





    Output:





[1, 'hi', 'Python', 2]




# List slicing  





print (list1[3:])  





  Output:





[2]




# List slicing  





print (list1[0:2])   





  Output:





[1, 'hi',]




# List Concatenation using + operator  





print (list1 + list1)  





output:-





  [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]




# List repetation using * operator  





print (list1 * 3)  





Output:





[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]




 





1. Create a List in Python





Lets see how to create a list in Python. To create a list all you have to do is to place the items inside a square bracket [] separated by comma ,.





# list of floats




num_list = [11.22, 9.9, 78.34, 12.0]




 




# list of int, float and strings




mix_list = [1.13, 2, 5, "sjkpgm", 100, "hi"]




 




# an empty list




nodata_list = []




a list can have data items of same type or different types. This is the reason list comes under compound data type.





 





2. Accessing the items of a list





Syntax to access the list items:





list_name[index]




Example:





# a list of numbers




numbers = [11, 22, 33, 100, 200, 300]




 




# prints 11




print(numbers[0])




 




# prints 300




print(numbers[5])




 




# prints 22




print(numbers[1])




Output:





11




300




22




Points to Note:
1. The index cannot be a float number.
For example:





# a list of numbers




numbers = [11, 22, 33, 100, 200, 300]




 




# error




print(numbers[1.0])




Output:





TypeError: list indices must be integers or slices, not float




2. The index must be in range to avoid IndexError.





The range of the index of a list having 10 elements is 0 to 9, if we go above 9 then we will get IndexError.
For example:





# a list of numbers




numbers = [5, 10, 15, 20, 25, 30,35]




 




# error




print(numbers[7])




Output:





IndexError: list index out of range




 





3. Negative Index to access the list items from the end





Python allows you to use negative indexes. The idea behind this to allow you to access the list elements starting from the end. For example an index of -1 would access the last element of the list, -2 second last, -3 third last and so on.





Example :-





# a list of strings




my_list = ["hello", "world", "hi", "bye"]




 




# prints "bye"




print(my_list[-1])




Output:





bye




 




# prints "world"




print(my_list[-3])




Output:





world




 




# prints "hello"




print(my_list[-4])




Output:





Hello




 




4. How to get a sub list in Python using slicing





We can get a sub list from a list in Python using slicing operation. Lets say we have a list n_list having 10 elements, then we can slice this list using colon : operator. Lets take an example to understand this:





 Slicing example





# list of numbers




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




 




# list items from 2nd to 3rd




print(n_list[1:3])




 




# list items from beginning to 3rd




print(n_list[:3])




 




# list items from 4th to end of list




print(n_list[3:])




 




# Whole list




print(n_list[:])




Output:





[2, 3]




[1, 2, 3]




[4, 5, 6, 7]




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




 





5. List Operations





There are various operations that we can perform on Lists.





1. Addition





There are several ways you can add elements to a list.





# list of numbers




n_list = [1, 2, 3, 4]




 




# 1. adding item at the desired location




# adding element 100 at the fourth location




n_list. Insert(3, 100)




 




# list: [1, 2, 3, 100, 4]




print(n_list)




 




# 2. adding element at the end of the list




n_list.append(99)




 




# list: [1, 2, 3, 100, 4, 99]




print(n_list)




 




# 3. adding several elements at the end of list




# the following statement can also be written like this:




# n_list + [11, 22]




n_list. Extend([11, 22])




 




# list: [1, 2, 3, 100, 4, 99, 11, 22]




print(n_list)




Output:





[1, 2, 3, 100, 4]




[1, 2, 3, 100, 4, 99]




[1, 2, 3, 100, 4, 99, 11, 22]




 





2. Update elements





We can change the values of elements in a List. Lets take an example to understand this:





# list of numbers




n_list = [1, 2, 3, 4]




 




# Changing the value of 3rd item




n_list[2] = 100




 




# list: [1, 2, 100, 4]




print(n_list)




 




# Changing the values of 2nd to fourth items




n_list[1:4] = [11, 22, 33]




 




# list: [1, 11, 22, 33]




print(n_list)




Output:





[1, 2, 100, 4]




[1, 11, 22, 33]




 





3. Delete elements





# list of numbers




n_list = [1, 2, 3, 4, 5, 6]




 




# Deleting 2nd element




del n_list[1]




 




# list: [1, 3, 4, 5, 6]




print(n_list)




 




# Deleting elements from 3rd to 4th




del n_list[2:4]




 




# list: [1, 3, 6]




print(n_list)




 




# Deleting the whole list




del n_list




Output:





[1, 3, 4, 5, 6]




[1, 3, 6]




 





4. Deleting elements using remove(), pop() and clear() methods





remove(item): Removes specified item from list.
pop(index): Removes the element from the given index.
pop(): Removes the last element.
clear(): Removes all the elements from the list.





# list of chars




ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']




 




# Deleting the element with value 'B'




ch_list.remove('B')




 




# list: ['A', 'F', 'Z', 'O', 'L']




print(ch_list)




 




# Deleting 2nd element




ch_list.pop(1)




 




# list: ['A', 'Z', 'O', 'L']




print(ch_list)




 




# Deleting all the elements




ch_list.clear()




 




# list: []




print(ch_list)




Output:





['A', 'F', 'Z', 'O', 'L']




['A', 'Z', 'O', 'L']




[]




 





=================================================================





Tuple





A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().





A tuple can have heterogeneous data items, a tuple can have string and list as data items as well.





A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.





example of the tuple.





tup  = ("hi", "Python", 2)    





# Checking type of tup  





print (type(tup))    





  Output:





<class 'tuple'>




#Printing the tuple  





print (tup)  





  Output:





('hi', 'Python', 2)




# Tuple slicing  





print (tup[1:])    





print (tup[0:1])    





  Output:





('Python', 2)




('hi',)




# Tuple concatenation using + operator  





print (tup + tup)    





  Output:





('hi', 'Python', 2, 'hi', 'Python', 2)




# Tuple repatation using * operator  





print (tup * 3)     





  Output:





('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)




# Adding value to tup. It will throw an error.  





t[2] = "hi"  





Output:





Traceback (most recent call last):




  File "main.py", line 14, in <module>




    t[2] = "hi";




TypeError: 'tuple' object does not support item assignment




 





Tuple vs List





  1. The elements of a list are mutable whereas the elements of a tuple are immutable.
  2. When we do not want to change the data over time, the tuple is a preferred data type whereas when we need to change the data in future, list would be a wise option.
  3. Iterating over the elements of a tuple is faster compared to iterating over a list.
  4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are enclosed in square bracket.




create a tuple in Python:-





To create a tuple in Python, place all the elements in a () parenthesis, separated by commas. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well.





Creating tuple





We can create tuples of homogenous and heterogenous data items





example :-





# tuple of strings




my_data = ("hi", "hello", "bye")




print(my_data)




 




# tuple of int, float, string




my_data2 = (1, 2.8, "Hello World")




print(my_data2)




 




# tuple of string and list




my_data3 = ("Book", [1, 2, 3])




print(my_data3)




 




# tuples inside another tuple




# nested tuple




my_data4 = ((2, 3, 4), (1, 2, "hi"))




print(my_data4)




Output:





('hi', 'hello', 'bye')




(1, 2.8, 'Hello World')




('Book', [1, 2, 3])




((2, 3, 4), (1, 2, 'hi'))




Empty tuple:





# empty tuple




my_data = ()




 





Tuple with only single element:





When a tuple has only one element, we must put a comma after the element, otherwise Python will not treat it as a tuple it will treat as an int variable.





.





# a tuple with single data item




my_data = (99,)




 





Accessing  tuple elements





We use indexes to access the elements of a tuple.





Example:-





  1. Accessing tuple elements using positive indexes




Indexes starts with 0 that is why we use 0 to access the first element of tuple, 1 to access second element and so on.





# tuple of strings




my_data = ("hi", "hello", "bye")




 




# displaying all elements




print(my_data)




 




# accessing first element




# prints "hi"




print(my_data[0])




 




# accessing third element




# prints "bye"




print(my_data[2])




Output:





('hi', 'hello', 'bye')




hi




bye




Note:
1. TypeError: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer.
2. IndexError: Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occurr.





 





2. Negative indexes in tuples





Similar to list and strings we can use negative indexes to access the tuple elements from the end. -1 to access last element, -2 to access second last and so on.





my_data = (1, 2, "Kevin", 8.9)




 




# accessing last element




# prints 8.9




print(my_data[-1])




 




# prints 2




print(my_data[-3])




Output:





8.9




2




 





3. Accessing elements from nested tuples





For this double indexes are used to access the elements of nested tuple. The first index represents the element of main tuple and the second index represent the element of the nested tuple.





Example:- my_data[2][1]





it accessed the second element of the nested tuple. Because 2 represented the third element of main tuple which is a tuple and the 1 represented the second element of that tuple.





my_data = (1, "Steve", (11, 22, 33))




 




# prints 'v'




print(my_data[1][3])




 




# prints 22




print(my_data[2][1])




Output:





v




22




 





Operations of tuple





the operations of tuples are :-





1. Changing the elements of a tuple





We cannot change the elements of a tuple because elements of tuple are immutable. But, we can change the elements of nested items that are mutable. For example, in the following code, we are changing the element of the list which is present inside the tuple. List items are mutable so it is allowed.





my_data = (1, [9, 8, 7], "World")




print(my_data)




 




# changing the element of the list




# this is valid because list is mutable




my_data[1][2] = 99




print(my_data)




 




# changing the element of tuple




# This is not valid since tuple elements are immutable




# TypeError: 'tuple' object does not support item assignment




# my_data[0] = 101




# print(my_data)




Output:





(1, [9, 8, 7], 'World')




(1, [9, 8, 99], 'World')




 





2. Delete operation on tuple





tuple elements are immutable which also means that we cannot delete the elements of a tuple. However deleting entire tuple is possible.





my_data = (1, 2, 3, 4, 5, 6)




print(my_data)




 




# not possible




# error




# del my_data[2]




 




# deleting entire tuple is possible




del my_data




 




# not possible




# error




# because my_data is deleted




# print(my_data)




Output:





(1, 2, 3, 4, 5, 6)




 





3. Slicing operation in tuples





my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)




print(my_data)




 




# elements from 3rd to 5th




# prints (33, 44, 55)




print(my_data[2:5])




 




# elements from start to 4th




# prints (11, 22, 33, 44)




print(my_data[:4])




 




# elements from 5th to end




# prints (55, 66, 77, 88, 99)




print(my_data[4:])




 




# elements from 5th to second last




# prints (55, 66, 77, 88)




print(my_data[4:-1])




 




# displaying entire tuple




print(my_data[:])




Output:





(11, 22, 33, 44, 55, 66, 77, 88, 99)




(33, 44, 55)




(11, 22, 33, 44)




(55, 66, 77, 88, 99)




(55, 66, 77, 88)




(11, 22, 33, 44, 55, 66, 77, 88, 99)




 





4. Membership Test in Tuples





in: Checks whether an element exists in the specified tuple.
not in: Checks whether an element does not exist in the specified tuple.





my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)




print(my_data)




 




# true




print(22 in my_data)




 




# false




print(2 in my_data)




 




# false




print(88 not in my_data)




 




# true




print(101 not in my_data)




Output:





(11, 22, 33, 44, 55, 66, 77, 88, 99)




True




False




False




True




 





5. Iterating a tuple





# tuple of fruits




my_tuple = ("Apple", "Orange", "Grapes", "Banana")




 




# iterating over tuple elements




for fruit in my_tuple:




     print(fruit)




Output:





Apple




Orange




Grapes




Banana




Others :-





# Python program to demonstrate accessing tuple





tuple1 = tuple([1, 2, 3, 4, 5])





# Accessing element using indexing





print("Frist element of tuple")





print(tuple1[0])





# Accessing element from last





# negative indexing





print("\nLast element of tuple")





print(tuple1[-1])





print("\nThird last element of tuple")





print(tuple1[-3])





Output:





Frist element of tuple





1





Last element of tuple





5





Third last element of tuple





3





================================================================





 





Dictionary





Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each key stores a specific value. Key can hold any primitive data type, whereas value is an random Python object. Dictionary is a mutable data type in Python.





The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}. Left side of the colon(:) is the key and right side of the : is the value.





Consider the following example.





d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}     





  • Keys must be unique in dictionary, duplicate values are allowed.
  • A dictionary is said to be empty if it has no key value pairs. An empty dictionary is denoted like this: {}.
  • The keys of dictionary must be of immutable data types such as String, numbers or tuples.




# Printing dictionary  





print (d)  





# Accessing value using keys  





print("1st name is "+d[1])   





print("2nd name is "+ d[4])    





print (d.keys())    





print (d.values())    





Output:





1st name is Jimmy




2nd name is mike




{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}




dict_keys([1, 2, 3, 4])




dict_values(['Jimmy', 'Alex', 'john', 'mike'])




 





example:-





mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}




Points to Note:





 





Accessing dictionary values using keys





To access a value by the corresponding key in the square brackets as shown in example.





mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}




print("Student Age is:", mydict['StuAge'])




print("Student City is:", mydict['StuCity'])




Output:
Python dictionary example





If you specify a key which doesn’t exist in the dictionary then you will get a compilation error.





For example. Here we are trying to access the value for key ‘StuClass’ which does not exist in the dictionary mydict, thus we get a compilation error when we run this code.





mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}




print("Student Age is:", mydict['StuClass'])




print("Student City is:", mydict['StuCity'])




Output:





 





Change values in Dictionary





You can update the values for the existing key-value pairs. To update a value in dictionary we use the corresponding key.





mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}




print("Student Age before update is:", mydict['StuAge'])




print("Student City before update is:", mydict['StuCity'])




mydict['StuAge'] = 31




mydict['StuCity'] = 'Noida'




print("Student Age after update is:", mydict['StuAge'])




print("Student City after update is:", mydict['StuCity'])




Output:
Python dictionary update values





 





Adding a new entry (key-value pair) in dictionary





We can also add a new key-value pair in an existing dictionary. example :-





mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}




mydict['StuClass'] = 'Jr.KG'




print("Student Name is:", mydict['StuName'])




print("Student Class is:", mydict['StuClass'])




Output:
Python adding new key value pair in dictionary





 





Loop through a dictionary





We can loop through a dictionary as shown in the following example. Here we are using for loop.





mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}




for e in mydict:




  print("Key:",e,"Value:",mydict[e])




Output:
Python loop through dictionary





 





Python delete operation on dictionary





We can delete key-value pairs as well as entire dictionary in python.





To delete all the entries (all key-value pairs) from dictionary we can use the clear() method.





To delete entire dictionary along with all the data use del keyword followed by dictionary name as shown in the following example.





mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}




del mydict['StuCity']; # remove entry with key 'StuCity'




mydict.clear();     # remove all key-value pairs from mydict




del mydict ;        # delete entire dictionary mydict




 





============================================================





Boolean





Boolean type provides two built-in values, True and False. These values are used to determine the given statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.  example:-





# Python program to check the boolean type  





print(type(True))  





print(type(False))  





print(false)  





Output:





<class 'bool'>




<class 'bool'>




NameError: name 'false' is not defined




 





=================================================================





Set





Set is the unordered and unindexed collection of items (data type). Unordered means random order. Unindexed means, we cannot access the elements of a set using the indexes like we can do in list and tuples.  It is iterate able, mutable(can modify after creation), and has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values.





(The elements of a set are defined inside square brackets and are separated by commas.)





Example:-





# Creating Empty set  





set1 = set()  





 set2 = {'James', 2, 3,'Python'}  





#Printing Set value  





print(set2)  





  Output: {3, 'Python', 'James', 2}




# Adding element to the set  





  set2.add(10)  





print(set2)  





 Output: {'Python', 'James', 3, 2, 10}




#Removing element from the set  





set2.remove(2)  





print(set2)  





Output: {'Python', 'James', 3, 10}




Example:





Set = {5,1,2.6,"python"} print(Set)




Output: {‘python', 1, 5, 2.6}





Example:





A = {'a', 'c', 'd'} B = {'c', 'd', 2 } print('A U B =', A| B)




Output: A U B = {‘c', ‘a’, 2, ‘d'}





A = {100, 7, 8} B = {200, 4, 7} print(A & B)




Output: {7}





For example –





myset = [1, 2, 3, 4, "hello"]




 





Example





# Set Example




myset = {"hi", 2, "bye", "Hello World"}




print(myset)




Output:
Python set example





Checking whether an item is in the set





We can check whether an item exists in Set or not using “in” operator . example:-





This returns the Boolean value true or false. If the item is in the given set then it returns true, else it returns false.





# Set Example




myset = {"hi", 2, "bye", "Hello World"}




 




# checking whether 2 is in myset




print(2 in myset)




 




# checking whether "hi" is in myset




print("hi" in myset)




 




# checking whether "BeginnersBook" is in myset




print("BeginnersBook" in myset)




Output:
Python checking an item in the Set





 





Loop through the elements of a Set





We can loop through the elements of a set in Python as shown in the following elements. As you can see in the output that the elements will appear in random order each time you run the code.





# Set Example




myset = {"hi", 2, "bye", "Hello World"}




 




# loop through the elements of myset




for a in myset:




    print(a)




Output:
Python set loop





Python – Add or remove item from a Set





We can add an item in a Set using add() function and we can remove an item from a set using remove() function as shown in the following example.





# Set Example




myset = {"hi", 2, "bye", "Hello World"}




print("Original Set:", myset)




 




# adding an item




myset.add(99)




print("Set after adding 99:", myset)




 




# removing an item




myset.remove("bye")




print("Set after removing bye:", myset)




Output:
Python add or remove item from a Set





Set Methods





1. add(): This method adds an element to the Set.
2. remove(): This method removes a specified element from the Set
3. discard(): This method works same as remove() method, however it doesn’t raise an error when the specified element doesn’t exist.
4. clear(): Removes all the elements from the set.
5. copy(): Returns a shallow copy of the set.
6. difference(): This method returns a new set which is a difference between two given sets.
7. difference_update(): Updates the calling set with the Set difference of two given sets.
8. intersection(): Returns a new set which contains the elements that are common to all the sets.
9. intersection_update(): Updates the calling set with the Set intersection of two given sets.
10. isdisjoint(): Checks whether two sets are disjoint or not. Two sets are disjoint if they have no common elements.
11. issubset(): Checks whether a set is a subset of another given set.
12. pop(): Removes and returns a random element from the set.
13. union(): Returns a new set with the distinct elements of all the sets.
14. update(): Adds elements to a set from other passed iterable.
15. symmetric_difference(): Returns a new set which is a symmetric difference of two given sets.
16. symmetric_difference_update(): Updates the calling set with the symmetric difference of two given sets.





============================================================





References: -





Web resources:-






https://www.datacamp.com/





https://www.w3schools.com/





https://www.programiz.com/





https://www.tutorialspoint.com/





https://docs.python.org/





https://www.geeksforgeeks.org/





https://www.guru99.com/

Post a Comment

0 Comments