Understanding Data Handling in Python

Slide Note
Embed
Share

Types of data in Python include Number, String, List, Tuple, Set, and Dictionary. Python supports integers, floating point numbers, and complex numbers with the classes int, float, and complex. Different number systems like binary, hexadecimal, and octal are also supported. Type conversion in Python can be implicit or explicit using built-in functions like int(), float(), and complex().


Uploaded on Oct 07, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Data Handling in Python The material is only for free educational purposes. Python 3.6.5

  2. Types of Data in Python Number String List Tuple Set Dictionary The material is only for free educational purposes.

  3. Python Data Types Python Data Types The material is only for free educational purposes. Number Boolean String Collection Integer Float Complex List Tuple Set Dictionary

  4. Number Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python. Integers and floating points are separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is a floating point number. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class. The material is only for free educational purposes.

  5. Example a = 5 # Output: <class 'int'> print(type(a)) # Output: <class bool'> k=True print(type(k)) The material is only for free educational purposes. # Output: <class 'float'> print(type(5.0)) # Output: (8+3j) c = 5 + 3j print(c + 3) # Output: True print(isinstance(c, complex))

  6. Support for Embedded Systems integers can be of any length. float is accurate only up to 15 decimal places (the 16th place is inaccurate). Python supports binary (base 2), hexadecimal (base 16) and octal (base 8) number systems which is needed by embedded. The material is only for free educational purposes. Binary '0b' or '0B' Octal '0o' or '0O' Hexadecimal '0x' or '0X'

  7. Example # Output: 107 print(0b1101011) # Output: 253 (251 + 2) print(0xFB + 0b10) The material is only for free educational purposes. # Output: 13 print(0o15)

  8. Type Conversion Implicit Conversion Automatic conversion by python is implicit conversion. Example: >>> 1 + 2.0 3.0 The material is only for free educational purposes. Explicit Conversion We can also use built-in functions like int(), float() and complex() to convert between types explicitly Example: >>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>> complex('3+5j') (3+5j)

  9. Python Decimal Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree. >>> (1.1 + 2.2) == 3.3 False To overcome this issue, we can use decimal module that comes with Python. import decimal # Output: 0.1 print(0.1) # Output: Decimal('0.100000000000000005551115123125782 70211815 83404541015625') print(decimal.Decimal(0.1)) The material is only for free educational purposes.

  10. Python Fractions Python provides operations involving fractional numbers through its fractions module. import fractions # Output: 3/2 print(fractions.Fraction(1.5)) # Output: 5 print(fractions.Fraction(5)) # Output: 1/3 print(fractions.Fraction(1,3)) The material is only for free educational purposes.

  11. Python Fractions Fortunately, Fraction allows us to instantiate with string as well. This is the preferred options when using decimal numbers. import fractions # As float # Output: 2476979795053773/2251799813685248 print(fractions.Fraction(1.1)) # As string # Output: 11/10 print(fractions.Fraction('1.1')) The material is only for free educational purposes. This datatype supports all basic operations. Here are few examples. from fractions import Fraction as F # Output: 2/3 print(F(1,3) + F(1,3)) # Output: 6/5 print(1 / F(5,6)) # Output: False print(F(-3,10) > 0) # Output: True print(F(-3,10) < 0)

  12. Python Mathematics Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and statistics, etc. import math # Output: 3.141592653589793 print(math.pi) # Output: -1.0 print(math.cos(math.pi)) # Output: 22026.465794806718 print(math.exp(10)) # Output: 3.0 print(math.log10(1000)) # Output: 1.1752011936438014 print(math.sinh(1)) # Output: 720 print(math.factorial(6)) The material is only for free educational purposes. Random module import random # Output: 16 print(random.randrange(10,20)) x = ['a', 'b', 'c', 'd', 'e'] # Get random choice print(random.choice(x)) # Shuffle x random.shuffle(x) # Print the shuffled x print(x) # Print random element print(random.random())

  13. Python List List is one of the most frequently used sequence and very versatile datatype used in Python. # empty list my_list = [] The material is only for free educational purposes. # list of integers my_list = [1, 2, 3] # list with mixed datatypes my_list = [1, "Hello", 3.4] Also, a list can even have another list as an item. This is called nested list. # nested list my_list = ["mouse", [8, 4, 6], ['a']]

  14. Using the list() constructor It is also possible to use the list() constructor to make a list. To add an item to the list use append() object method. To remove a specific item use the remove() object method. The len() function returns the length of the list. thislist = list(("apple", "banana", "cherry")) # note the double round- brackets thislist.append("damson") print(thislist) The material is only for free educational purposes.

  15. Access elements from a list List Index We can use the index operator [] to access an item in a list. Index starts from 0. my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1]) # Output: 5 print(n_list[1][3]) 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. my_list = ['p','r','o','b','e'] # Output: e print(my_list[-1]) # Output: p print(my_list[-5]) The material is only for free educational purposes.

  16. How to slice lists in Python? We can access a range of items in a list by using the slicing operator (colon). my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) The material is only for free educational purposes.

  17. How to change or add elements to a list? We can use assignment operator (=) to change an item or a range of items. # mistake values odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 # Output: [1, 4, 6, 8] print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] # Output: [1, 3, 5, 7] print(odd) The material is only for free educational purposes. We can add one item to a list using append() method or add several items using extend()method. odd = [1, 3, 5] odd.append(7) # Output: [1, 3, 5, 7] print(odd) odd.extend([9, 11, 13]) # Output: [1, 3, 5, 7, 9, 11, 13] print(odd) odd = [1, 9] odd.insert(1,3) # Output: [1, 3, 9] print(odd)

  18. How to delete or remove elements from a list? We can delete one or more items from a list using the keyword del. It can even delete the list entirely. my_list = ['p','r','o','b','l','e','m'] # delete one item del my_list[2] # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list) # delete multiple items del my_list[1:5] # Output: ['p', 'm'] print(my_list) # delete entire list del my_list # Error: List not defined print(my_list) The material is only for free educational purposes.

  19. How to delete or remove elements from a list? The pop() method removes and returns the last item if index is not provided. This helps us implement lists as stacks (first in, last out data structure). We can also use the clear() method to empty a list. my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list) The material is only for free educational purposes.

  20. Python List Methods append() - Add an element to the end of the list extend() - Add all elements of a list to the another list insert() - Insert an item at the defined index remove() - Removes an item from the list The material is only for free educational purposes. pop() - Removes and returns an element at the given index clear() - Removes all items from the list index() - Returns the index of the first matched item count() - Returns the count of number of items passed as an argument sort() - Sort items in a list in ascending order reverse() - Reverse the order of items in the list copy() - Returns a shallow copy of the list

  21. Elegant way to create new List List comprehension consists of an expression followed by for statement inside square brackets. pow2 = [2 ** x for x in range(10)] # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] print(pow2) The material is only for free educational purposes. This code is equivalent to pow2 = [] for x in range(10): pow2.append(2 ** x)

  22. Tuple In Python programming, a tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. Advantages of Tuple over List Since, tuples are quite similiar to lists, both of them are used in similar situations as well. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages: We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost. Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible. If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected. The material is only for free educational purposes.

  23. Creating a Tuple A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it. A tuple can have any number of items and they may be of different types (integer, float, list, string etc.). # empty tuple # Output: () my_tuple = () print(my_tuple) # tuple having integers # Output: (1, 2, 3) my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes # Output: (1, "Hello", 3.4) my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple # Output: ("mouse", [8, 4, 6], (1, 2, 3)) my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple) # tuple can be created without parentheses # also called tuple packing The material is only for free educational purposes.

  24. Creating Tuple with one element Creating a tuple with one element is a bit tricky. Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is in fact a tuple. # only parentheses is not enough # Output: <class 'str'> my_tuple = ("hello") print(type(my_tuple)) # need a comma at the end # Output: <class 'tuple'> my_tuple = ("hello",) print(type(my_tuple)) # parentheses is optional # Output: <class 'tuple'> my_tuple = "hello", print(type(my_tuple)) The material is only for free educational purposes.

  25. Built-in Functions with Tuple Function Description Return True if all elements of the tuple are true (or if the tuple is empty). all() Return True if any element of the tuple is true. If the tuple is empty, return False. any() Return an enumerate object. It contains the index and value of all the items of tuple as pairs. enumerate() The material is only for free educational purposes. len() Return the length (the number of items) in the tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple Take elements in the tuple and return a new sorted list (does not sort the tuple itself). sorted() sum() Retrun the sum of all elements in the tuple. tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

  26. Set A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed). However, the set itself is mutable. We can add or remove items from it. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. The material is only for free educational purposes.

  27. How to create a set? # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) The material is only for free educational purposes.

  28. How to create EMPTY set? Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument. # initialize a with {} a = {} # check data type of a # Output: <class 'dict'> print(type(a)) # initialize a with set() a = set() # check data type of a # Output: <class 'set'> print(type(a)) The material is only for free educational purposes.

  29. How to change a set in Python? Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it. We can add single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. # initialize my_set my_set = {1,3} print(my_set) # if you uncomment line 9, # you will get an error # TypeError: 'set' object does not support indexing #my_set[0] # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8}) print(my_set) The material is only for free educational purposes.

  30. Python Set Operations Union is performed using | operator. Same can be accomplished using the method union(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) Intersection is performed using & operator. Same can be accomplished using the method intersection(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) The material is only for free educational purposes.

  31. Python Set Operations Difference is performed using - operator. Same can be accomplished using the method difference(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) The material is only for free educational purposes.

  32. Python Set Methods Method Description add() Add an element to a set clear() Remove all elements form a set copy() Return a shallow copy of a set Return the difference of two or more sets as a new set difference() difference_update() Remove all elements of another set from this set Remove an element from set if it is a member. (Do nothing if the element is not in set) discard() The material is only for free educational purposes. intersection() Return the intersection of two sets as a new set Update the set with the intersection of itself and another intersection_update() isdisjoint() Return True if two sets have a null intersection issubset() Return True if another set contains this set issuperset() Return True if this set contains another set Remove and return an arbitary set element. Raise KeyErrorif the set is empty pop() Remove an element from a set. If the element is not a member, raise a KeyError remove() Return the symmetric difference of two sets as a new set symmetric_difference() Update a set with the symmetric difference of itself and another symmetric_difference_update() union() Return the union of sets in a new set

  33. Dictionary Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known. The material is only for free educational purposes.

  34. How to create a dictionary? # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} The material is only for free educational purposes. # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')])

  35. Access elements from a Dictionary While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. The difference while using get() is that it returns None instead of KeyError, if the key is not found. my_dict = {'name':'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # my_dict.get('address') # my_dict['address'] The material is only for free educational purposes.

  36. Change or add elements in a dictionary Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary. my_dict = {'name':'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict) The material is only for free educational purposes.

  37. Python Dictionary Comprehension squares = {x: x*x for x in range(6)} # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} print(squares) The material is only for free This code is equivalent to squares = {} for x in range(6): squares[x] = x*x educational purposes.

  38. Python Dictionary Methods Method Description clear() Remove all items form the dictionary. copy() Return a shallow copy of the dictionary. Return a new dictionary with keys from seq and value equal to v(defaults to None). fromkeys(seq[, v]) Return the value of key. If key doesnot exit, return d (defaults to None). get(key[,d]) items() Return a new view of the dictionary's items (key, value). The material is only for free educational purposes. keys() Return a new view of the dictionary's keys. Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. pop(key[,d]) Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. popitem() If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). setdefault(key[,d]) Update the dictionary with the key/value pairs from other, overwriting existing keys. update([other]) values() Return a new view of the dictionary's values

  39. Strings # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string) The material is only for free educational purposes.

  40. How to access characters in a string? str = Allahabad' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2]) The material is only for free educational purposes.

  41. Iterating Through String Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a string. count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found') The material is only for free educational purposes.

  42. String Membership Test We can test if a sub string exists within a string or not, using the keyword in. >>> 'a' in 'program' True >>> 'at' not in 'battle' False The material is only for free educational purposes.

  43. Escape Sequence in Python Escape Sequence Description \newline Backslash and newline ignored \\ Backslash \' Single quote \" Double quote ASCII Bell \a The material is only for free educational purposes. \b ASCII Backspace \f ASCII Formfeed \n ASCII Linefeed \r ASCII Carriage Return \t ASCII Horizontal Tab \v ASCII Vertical Tab \ooo Character with octal value ooo \xHH Character with hexadecimal value HH

  44. Raw String to ignore escape sequence Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored. >>> print("This is \x61 \ngood example") This is a good example >>> print(r"This is \x61 \ngood example") This is \x61 \ngood example The material is only for free educational purposes.

  45. The format( ) Method for Formatting Strings # default(implicit) order default_order = "{}, {} and {}".format('John','Bill','Sean') print('\n--- Default Order ---') print(default_order) The material is only for free educational purposes. # order using positional argument positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('\n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean') print('\n--- Keyword Order ---') print(keyword_order)

  46. Old style formatting >>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457 The material is only for free educational purposes.

  47. Common Python String Methods Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc. >>> AlLaHabad".lower() allahabad' >>> " AlLaHabad ".upper() ALLAHABAD The material is only for free educational purposes. >>> "This will split all words into a list".split() ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list'] >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string']) 'This will join all words into a string >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year'

  48. The format( ) Method for Formatting Strings >>> # formatting integers >>> "Binary representation of {0} is {0:b}".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: {0:e}".format(1566.345) 'Exponent representation: 1.566345e+03' The material is only for free educational purposes. >>> # round off >>> "One third is: {0:.3f}".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham') '|butter | bread | ham|'

  49. The material is only for free educational purposes. Thanks The material is only for free educational purposes.

Related