Data Structures and Algorithms in Python | Set 1Data structures and algorithms or DSA is the concept in programming that every programmer has to be perfect in, to create a code by efficiently making the best use of the available resources. Irrespective of the programming language, DSA is more of a general concept. This tutorial covers the basic foundation of DSA using the Python programming language. Data structures:"Data + structures" says it all. A data structure structures the data. It is a storage unit that organizes and stores data in a way the programmer can easily access. In the real world, a programmer/ coder's work involves huge amounts of data. Analyzing and using the data is made easy for the programmer when it is arranged the right way. Apart from organizing the data, Data structures also makes processing and accessing the data easy. This tutorial covers all of Python's Data structures. There are built-in data structures as well as user-defined data structures. Let's first look at the built-in ones: 1. ListsA list is like a dynamic and heterogeneous array. Arrays are used in languages like C. Unlike arrays, lists are dynamically-sized and can store data of different types. It is one of the sequential data types in Python. Important points about Lists:
Most used Functions and Methods:
Example: Output: Created lists: emptylist: [] mylist: [20, 20, 'H', 'Hello'] nestedlist: [[1, 2], [20, 20, 'H', 'Hello']] Concatenating mylist and nestedlist: [20, 20, 'H', 'Hello', [1, 2], [20, 20, 'H', 'Hello']] Repeating the elements of a list: [20, 20, 'H', 'Hello', 20, 20, 'H', 'Hello', 20, 20, 'H', 'Hello'] List as an input: Enter elements(separate by space):8 9 7 8 [8, 9, 7, 8] In the nested list: (Normal)nestedlist[0]: [1, 2] (Negative)nestedlist[-2]: [1, 2] Adding elements to the empty list: emptylist: [1, 3, 4, 5] Adding an index emptylist[1]: [1, 2, 3, 4, 5] Extending mylist with emptylist: None Using Slicing Slicing mylist[:]: [20, 20, 'H', 'Hello', 1, 2, 3, 4, 5] Reverse using slicing[::-1]: [5, 4, 3, 2, 1, 'Hello', 'H', 20, 20] Slicing using indices[1:3]: [20, 'H'] Creating a newlist[] using list comprehension: newlist with even elements in emptylist: [2, 4] Using functions: Length using len(): 9 Removing an element using remove: None Removing the last element using pop: 5 Using index(): 5 Using reverse on [1, 2, 3, 4, 5] : [5, 4, 3, 2, 1] Tuples:A Tuple is like an immutable list. It is also a sequence data type in Python and can store data of different data types, like a list, but unlike a list, we cannot alter a tuple once created; Python raises an error if we try. Example: Output: nestedtuple.append(1) AttributeError: 'tuple' object has no attribute 'append.'
Example: Output: [1, 2, 1] ([1, 2, 1], (1, 'h', 'Hello')) Important points about Tuples:
Most used Functions and Methods:
Example: Output: Emptytuple: () mytuple: (1, 'h', 'Hello') nestedtuple: ([1, 2], (1, 'h', 'Hello')) By Tuple packing: (1, 'Hi') Using tuple(): (1, 2, 3) Tuple with one element: (1,) Concatenating nestedtuple and mytuple: ([1, 2], (1, 'h', 'Hello'), 1, 'h', 'Hello') Repeating the elements of a tuple: (1, 'h', 'Hello', 1, 'h', 'Hello', 1, 'h', 'Hello') Tuple as an input: Enter elements(separate by space):3 4 5 (3, 4, 5) Slicing mytuple[:]: (1, 'h', 'Hello') Reverse using slicing[::-1]: ('Hello', 'h', 1) Slicing using indices[1:3]: ('h', 'Hello') Accessing elements: In nestedtuple[0]: [1, 2] In nestedtuple[-2]: [1, 2] By tuple unpacking: 1 h Hello Using the built-in functions: Length of mytuple: 3 Sorting a tuple using sorted(): [0, 1, 2] Using max(): 23 Using min(): 1 Using sum(): 10 Using all(): False Using any(): True Using count(): 2 Sets:A set is a collection of unique elements which does not support duplicate elements like lists and tuples. Another important point about Sets is that they are unordered, which makes accessing their elements using indexes impossible. Important points about Sets:
Output: set1 = {[1, 2], 2, 3} TypeError: unhashable type: 'list' Most used Functions and Methods on Sets:
Set Operators:
Example: Output: Creating a set: Empty set: set() Myset: {1, 2, 3} Nestedset: {3, (1, 2), 4} Removing duplicacy using set(): {1, 2} Enter elements: 10 11 12 inputset: {10, 11, 12} Frozen set: ({1, 2, 3, 4, 5}) Adding to emptyset: {'a'} Union of {1, 2, 3} and {3, (1, 2), 4} : {1, 2, 3, (1, 2), 4} Intersection of {1, 2, 3} and {3, (1, 2), 4} : {3} Difference of {1, 2, 3} and {3, (1, 2), 4} : {1, 2} Clearing emptyset: set() Membership operator to check if (1, 2) is in nestedset: True Equivalency on myset and nested set: False Subset operator to check if {1} is a subset of nestedset: False proper subset operator to check if {1} is a proper subset of nestedset: False Superset operator to check if nestedset is a superset of {1}: False proper superset operator to check if nestedset is a proper superset of {1}: False Elements in either myset or nestedset but not in both: {1, 2, (1, 2), 4}
DictionaryA dictionary is a collection of {key: value} pairs. Keys map values, and to access the values, in the places of indexes, we need to use the keys. It is an unordered collection of data. Important points about a Dictionary:
Most used dict Functions and Methods:
Example: Output: Enter keys: 1 2 3 Enter value for 1: a Enter value for 2: b Enter value for 3: c Created dictionaries: Emptydict: {} mydict1: {1: 'A', 2: 'B', 3: 'C'} mydict2: {4: 'D', 'E': 5} mydict3: {6: 'F', 7: 'G'} nesteddict: {1: {1: 'A', 2: 'B', 3: 'C'}, 2: {4: 'D', 'E': 5}} inputdict: {1: 'a', 2: 'b', 3: 'c'} Altering mydict2: {4: 'D', 5: 'E'} Adding elements to mydict3: {6: 'F', 7: 'G', 8: 'H', 9: ('I', 'J', 'K')} Using get() to access: mydict1.get(1): A Using keys() on {1: 'A', 2: 'B', 3: 'C'} : dict_keys([1, 2, 3]) using values() on {1: 'A', 2: 'B', 3: 'C'} : dict_values(['A', 'B', 'C']) Using items() on {1: 'A', 2: 'B', 3: 'C'} : dict_items([(1, 'A'), (2, 'B'), (3, 'C')]) Updating {1: 'A', 2: 'B', 3: 'C'} with {4: 'D', 5: 'E'} : {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'} Deleting a value using pop(): B {1: 'A', 3: 'C', 4: 'D', 5: 'E'} Strings:A string is an array of bytes/ characters. In C, we declare a string as a character array. In Python, there is no character data type. Characters do exist, but they are recognized as strings with length 1. A string is immutable, meaning we can't modify it once created. Important points about Strings:
Output: TypeError: 'str' object does not support item assignment Example: Output: TypeError: 'str' object doesn't support item deletion
Example: To represent a floating-point number, we can use %a.bf where a represents the number of digits we want in the representation and b represents the number of digits we want after the decimal point. Output: 0.26 Example: Output: Created strings: Hi Hi Hello Man The first character string1[0]: H The first character string[-2]: H Substrings of string3: string3[0:6]: Hello string3[-6:-1]: Ma Reversing using slicing-string3[::-1]: naM olleH Enter a string: What's up inputstring:: What's up Reassigning string2 to Hello: Present: Hi After reassigning: Hello Using escape sequences to escape single quotes, double quotes and backslashes Hi it's my pen I read a book called "It ends with us" yesterday The file is stored in the path: C:\Media\Documents\ Printing in a new line: Hi man Urging a tab space: Hi man The sum of 4 and 5: 9 The difference between 5 and 4: 9 The product of 4 and 5: 20 Strings are one of the most used data types in Python. Hence, the number of concepts, methods and functions for strings are adequate in the libraries of Python. Some very important Functions and Methods:
Bytearray:First: 1 byte = 8 bits(varies system-wise). A bytearray, as the name suggests, is an array of bytes. It is a collection of bytes. It can represent integers ranging from 0 to 256. It is one of the sequence data types in Python. A string is a sequence of Unicode characters, and a bytearray is a sequence of bytes. Important points about a Bytearray:
Example: Output: Created bytearray: bytearray(b'\x01\x02\x03\x04') Type: <class 'bytearray'> Elements of bytearray: 1 2 3 4 BA[2]: 3 Modifying BA[2] to 20: bytearray(b'\x01\x02\x06\x04') Adding elements: bytearray(b'\x01\x02\x06\x04\x07') bytearray():The function can construct a bytearray object and convert other objects to a bytearray object. The syntax of the function:
Example: Output: bytearray(b'') Summary: In this tutorial, we learned about the built-in data structures in Python:
In the second part of this tutorial, we'll learn about user-defined data structures like Linked lists, Trees, and heaps in Python. Next TopicGaussian Elimination in Python |