Data structures are essential in programming. They are used to organize, store, and manage data in a way that is efficient to access and modify.
Imagine doing your weekly load of laundry. Ideally, you separate socks, tees, trousers, and delicates in separate drawers for easy access in the morning before heading out. You are getting ready with a data structure. Now, imagine throwing all of those belongings either inside of one single drawer or multiple drawers without organization. How long do you think it will take for you to get decent for work or a night out? This is getting ready without a data structure.
In this article, we dive into the built-in data structures Python has to offer.
Built-in Data Structures in Python
Built-in data structures in Python include lists, dictionaries, tuples, and sets.
Lists
Lists are mutable (capable of alterations) data structures that can have dissimilar elements or parts. In other words, a single list can contain various different data types.
list = ['string', 300, (2, 4), 'that previous data type was a tuple']
The list data structure has 11 methods used to add, remove, or manipulate the list itself.
Adding Elements into a List
- append(): The append() method adds a single item onto a list
list = ['string, next is tupel', (2, 1), 3] list.append(500) print(list) # prints ['string, next is tupel', (2, 1), 3, 500]
- extend(): The extend() method appends the list by all items from the iterable. It differs from append() in the following way.
list = ['string, next is tupel', (2, 1), 3] list.append((8, 9)) print(list) # prints ['string, next is tupel', (2, 1), 3, (8, 9)] # Notice that append() leave (8, 9) as a tuple
list = ['string, next is tupel', (2, 1), 3] list.extend((8, 9)) print(list) # prints ['string, next is tupel', (2, 1), 3, 8, 9] # Notice that extend() did not leave (8, 9) as a tuple
- insert(): The insert() method inserts an item at a given position or index. The first argument being the index of the element that needs to be inserted, the second argument being the element itself.
list = ['string, next is tupel', (2, 1), 3] list.insert(0, 700) print(list) # prints [700, 'string, next is tupel', (2, 1), 3] # inserted 700 in the 0 index
Removing Elements from a List
- remove(): The remove() method removes the first item on the list that contains the value it was given.
list = ['string, next is tupel', (2, 1), 3, 8, 3] list.remove(3) print(list) # prints ['string, next is tupel', (2, 1), 8, 3]
- pop(): The pop() method removes a value in the position it was given, however if no index is given, it removes the last item.
list = ['string, next is tupel', (2, 1), 3] list.pop(0) print(list) # prints [(2, 1), 3]
list = ['string, next is tupel', (2, 1), 3] list.pop() print(list) # prints ['string, next is tupel', (2, 1)]
- clear(): The clear() method takes no arguments. It removes all items from the list.
list = ['string, next is tupel', (2, 1), 3] list.clear() print(list) # prints []
Other List Methods
- index(): The index() method returns the index of the value given.
list = [8, 20, 1, 9, 2, 3, 937, 0] print(list.index(9)) # prints 3
- count(): The count() method counts how many times a value occurs in a list.
list = [8, 20, 1, 8, 2, 8, 937, 8] print(list.count(8)) # prints 4
- sort(): The sort() method can be used with or without arguments and can be used for sorting customization.
list = [8, 20, 1, 9, 2, 3, 937, 0] list.sort() print(list) # prints [0, 1, 2, 3, 8, 9, 20, 937]
list = [8, 20, 1, 9, 2, 3, 937, 0] list.sort(reverse= True) print(list) # prints [937, 20, 9, 8, 3, 2, 1, 0]
- reverse(): The reverse method reverses the elements of the list in place, much like the sort method above that takes a customized sorting argument.
list = [8, 20, 1, 9, 2, 3, 937, 0] list.reverse() print(list) # prints [0, 937, 3, 2, 9, 1, 20, 8]
- copy(): The copy() method simply returns a copy of a list.
list = [8, 20, 1, 9, 2, 3, 937, 0] list.copy() print(list) # prints [8, 20, 1, 9, 2, 3, 937, 0]
Tuples
Tuples are data held in parenthesis. Unlike lists, they are not mutable (meaning it is not capable of alterations), and they are faster than lists. Because they are immutable, we can also use them as keys in dictionaries. Tuples can also be used for whenever we want to return multiple results from a function.
We can add data into a tuple by using concatenation.
tuple = (1, 2, 3) print(tuple) # prints (1, 2, 3) tuple = tuple + (4, 5, 6) print(tuple) # prints (1, 2, 3, 4, 5, 6)
Dictionaries
Dictionaries are data structures that hold key value pairs like objects in JavaScript. Like lists, these data structures are mutable, meaning we can change its data.
An example of a key value pair is the characteristics of a person and the description of those characteristics. Name, age, height, and weight can all be keys. Josh, 33, 5’10, 180 lbs, can all be values for those keys.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' }
Because dictionaries are mutable, we can change ‘Josh’ to another name.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } dict['name'] = 'Patrick' print(dict) # prints {'name': 'Patrick', 'age': 33, 'height': "5'10", 'weight': '180 lbs'}
We can add values by creating new key value pairs.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } dict['location'] = 'San Francisco' print(dict) # prints {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs', 'location': 'San Francisco'}
We can also delete key value pairs in a dictionary by utilizing the del keyword, pop(), or popitem() methods. Note that with dictionaries pop() must take an argument, so we need popitem() to remove from the last key value pair from a dictionary.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } del dict['name'] print(dict) # prints {'age': 33, 'height': "5'10", 'weight': '180 lbs'}
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } dict.pop('name') print(dict) # prints {'age': 33, 'height': "5'10", 'weight': '180 lbs'}
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } dict.popitem() print(dict) # prints {'name': 'Josh', 'age': 33, 'height': "5'10"}
We can also print solely the keys or solely the values of a dictionary.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } print(dict.keys()) # prints dict_keys(['name', 'age', 'height', 'weight'])
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } print(dict.values()) # prints dict_values(['Josh', 33, "5'10", '180 lbs'])
To print as key value pairs, we can use the items() method.
dict = {'name': 'Josh', 'age': 33, 'height': "5'10", 'weight': '180 lbs' } print(dict.items()) # prints dict_items([('name', 'Josh'), ('age', 33), ('height', "5'10"), ('weight', '180 lbs')])
Sets
Sets are mutable, unordered collections of unique elements, meaning they do not include duplicate elements. Sets look like dictionaries in that they both hold data in curly brackets, but unlike dictionaries, sets do not have key value pairs.
set = {1, 2, 2, 2, 3, 3, 4, 4} print(set) # prints {1, 2, 3, 4}
We can add elements to the set by utilizing the add() method.
set = {1, 2, 2, 2, 3, 3, 4, 4} set.add(5) print(set) # print {1, 2, 3, 4, 5}
There are four other methods available to us when using sets, union(), intersection(), difference(), and symmetric_difference().
- union(): The union() method unionizes two difference sets, taking the commonalities of both and producing it as a single set with no duplicates.
set = {1, 2, 2, 2, 3, 3, 4, 4} set.add(5) print(set) # prints {1, 2, 3, 4, 5} anotherSet = {3, 3, 4, 4, 5, 5, 6} print(set.union(anotherSet)) # prints {1, 2, 3, 4, 5, 6}
- intersection(): The intersection method finds the common elements in both sets.
set = {1, 2, 2, 2, 3, 3, 4, 4} set.add(5) print(set) # prints {1, 2, 3, 4, 5} anotherSet = {3, 3, 4, 4, 5, 5, 6} print(set.intersection(anotherSet)) # prints {3, 4, 5}
- difference(): The difference method does the opposite of the intersection method in that it takes out all of the commonalities and prints out what is left from the first set.
set = {1, 2, 2, 2, 3, 3, 4, 4} set.add(5) print(set) # prints {1, 2, 3, 4, 5} anotherSet = {3, 3, 4, 4, 5, 5, 6} print(set.difference(anotherSet)) # prints {1, 2}
- symmetric_difference(): The symmetric_difference() method is the same as the difference method except we get the difference of both of the sets in the output.
set = {1, 2, 2, 2, 3, 3, 4, 4} set.add(5) print(set) # prints {1, 2, 3, 4, 5} anotherSet = {3, 3, 4, 4, 5, 5, 6} print(set.symmetric_difference(anotherSet)) # prints {1, 2, 6}
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.