Built-in data structures in Python are pre-defined containers used to store and organize data. Examples include lists, tuples, dictionaries, and sets.
Key takeaways:
Python provides a diverse range of built-in data structures, including primitive types (integers, strings) and non-primitive types (lists, tuples, dictionaries, and sets) for effective data management.
Beyond built-in options, Python supports user-defined data structures (stacks, queues, trees, linked lists) to solve complex problems.
Python's data structures offer versatility and ease of use, enabling developers to write optimized and maintainable code.
Python comes with several inbuilt data structures widely used for storing and managing data. These can be categorized into primitive, non-primitive, and user-defined data structures.
my_list = [1, 2, 3, 'Python']
my_tuple = (1, 2, 3, 'Python')
my_dict = {'name': 'Alice', 'age': 25}
my_set = {1, 2, 3, 4}
Stack: A linear data structure following the LIFO (Last In, First Out) principle, where the last element added is the first to be removed.
Queues: A linear data structure following the FIFO (First In, First Out) principle, where the first element added is the first to be removed.
Tree: A hierarchical data structure consisting of nodes, with one root node and children forming a branching structure.
Linked List: A linear data structure where elements (nodes) are linked together via pointers, with each node pointing to the next.
Let’s discuss the built-in data structures one by one.
Lists are mutable, i.e., we can change the value of lists by using certain operations.
Lists can store heterogeneous data types.
lst = [1, 2, 3, 4, "a", "b", "c", 38.5, "56.7"]print(lst)print(type(lst))print(type(lst[-1]))
append()
)This adds an element at the end of the list:
l1 = [1, 2, 3, 4, 5, 6]l1.append(7)print(l1)
insert()
)This inserts an element at a specific index:
l1=[1, 2, 3, 4, 5, 6]l1.insert(2, 6)print(l1)
count
)This counts the occurrences of a character/number.
l2 = [1, 2, 3, 4, 5, "a", "a", "b", 1, 2, 4]s = l2.count(4)print(s)
The sorted()
function returns a new sorted list while leaving the original iterable unchanged. It works with any iterable, including lists, tuples, and strings, and always returns a new list. On the other hand, the sort()
method is specific to lists and modifies the original list in place, meaning it does not create a new one. Here’s an example showcasing the difference between the sorted()
function and the sort()
method in Python:
a = ["b", "g", "a", "d", "f", "c", "h", "e"]x = sorted(a)print("a after sorted function")print(a)print(x)b = [1, 2, 5, 8, 3]b.sort()print(b)
We use this function to extract certain elements in a list:
lst = [1, 2, 3, 4, 5, 6, 7]print(lst[0:4])print(lst[::])print(lst[::-1])
Line 2: Slices the list from index 0 to 3 (end index is exclusive), so the output is [1, 2, 3, 4]
.
Line 3: Returns the entire list with the default step of 1, so the output is [1, 2, 3, 4, 5, 6, 7]
.
Line 4: Reverses the list with a step of -1, so the output is [7, 6, 5, 4, 3, 2, 1]
.
There are three functions used to delete elements in a list:
pop()
: Removes and returns an element at a specified index (default is the last element).remove()
: Removes and returns an element at a specified index (default is the last element).clear()
: Removes all elements from the list, leaving it empty.lst = [1, 2, 3, 4, 5, 6, 7]print(lst.pop())print(lst)lst.remove(4)print(lst)lst.clear()print(lst)
A tuple is a collection of objects that are ordered and immutable. Like lists, tuples are sequences. The differences between tuples and lists are:
Unlike lists, tuples cannot be changed
tuples
are represented using ()
brackets
tuples
contain heterogeneous values
t = (1, 2, 3, 4, 5, "a", "b", "c")t1 = 1, 2, 3, 4, "g", "l"print(t)print(t1)print(len(t))
There is no append function in a tuple, but there is an indirect way of adding elements into the function:
t1 = (1, 2, 3, 4, 5)t2 = (6, 7, 8, 9)t3 = t1 + t2print(t3)
max()
: Prints a maximum value in the tuple.
min()
: Prints a minimum value in the tuple.
t = (1, 2, 3, 4, 5)print("Minimum element in the tuple",min(t))print("Maximum element in the tuple",max(t))
A dictionary is an unordered collection of data values used to store data values like a map. Unlike other data types that hold only a single value as an element, Dictionary holds a key value pair.
dictionary
is represented by{}
dict = {1:'a', 2:'b', 5:'c', 4:'d'}print(dict)print(dict[5])
pop()
deletes certain keys in the dictionary.popitem()
deletes the last element in the dictionary.clear()
erases all the key-value pairs in the dictionary.cubes = {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}print(cubes.pop(4))print(cubes)print(cubes.popitem())print(cubes)cubes.clear()print(cubes)
key()
is used to access the key values in a dictionaryvalues()
is used to access the values of the dictionary.items()
is used to access the key-value pair.d = {1:'10', 2:'20', 3:'30', 4:'40', 5:'50'}l1 =list(d.keys())print("the key values are:")print(l1)l2 = list(d.values())print("The values are of dictionary is")print(l2)l3 = list(d.items())print("the list items are")print(l3)
remove()
function removes certain elements in the set.set1 = {1, 2, 3, 4, "hi", "world", "python"}print("python" in set1)set1.remove(4)print(set1)
The code demonstrates set operations in Python to compare two sets, a
and b
, and extract specific relationships between their elements. The operation a ^ b
computes the symmetric difference, which returns elements that are in either set a
or b
but not in both; in this case, the result is {1, 4, 6, 7}
.
The operation a - b
finds the difference, returning elements that exist in the set a
but not in the set b
, resulting in {1, 4}
. Similarly, b - a
computes the difference in the opposite direction, returning elements in the set b
but not in the set a
, which yields {6, 7}
. These operations are useful for identifying unique elements or comparing datasets in Python.
a = {1, 2, 3, 4, 5}b = {2, 3, 6, 7, 5}c = a^bprint(c)d = a - bprint(d)e = b - aprint(e)
Ready to solve real-world problems with Python? “Data Structures and Algorithms in Python” teaches you essential data structures and algorithms, complete with coding exercises to ace typical interview questions.
Python offers a rich set of inbuilt data structures that cater to a wide range of data management needs. From primitive structures like integers and strings to non-primitive ones like lists, dictionaries, tuples, and sets, Python provides flexibility and efficiency in handling data. Additionally, user-defined data structures such as stacks, queues, trees, and linked lists expand Python’s capabilities, enabling developers to solve complex problems and build robust applications. By effectively understanding and leveraging these structures, Python programmers can write cleaner, more optimized code tailored to specific use cases.
Haven’t found what you were looking for? Contact Us