Introduction
The purpose of this article is to give you an overview of data structures in python. A good grasp of data structures and algorithms and the ways to implement them will assist you solve challenges using code and create robust solutions to real world problems.
What is a data structure?
The specific way of organizing, managing and storing data in a computer is called a data structure. This efficient way of managing data allows us to perform various operations in the data such as adding, appending and removing as per the requirement of the programs.
Types of data structures
In this article we will be covering only the built in data structures.
List
List is a type of data structure that contains a number of objects in a precise order to form a sequence to which elements can be added or removed. Each item is marked with a number corresponding to the order of the sequence, called index. In python index start at 0.
>>> list = [1,2,3,4]
>>> list
[1,2,3,4]
List comprehension
This is basically creating a new list from a previous list.
The syntax of list comprehension is new_list = [ new_item for item in list
] in which the new_item are values in your new_list.
Dictionaries
Dictionaries are really useful as they help to group together and tag related pieces of information.
Dictionaries are data structures in which a particular value is associated with a key value.
The dictionary syntax is dict={"name":"kelvin", "age":12,}
in which the name and age are the keys while kelvin and 12 are the values. Note that items in a dictionary are separated using a comma.
Retrieving data from a dictionary.
if you want to retrieve a piece af data from a dictionary, you just tap into the dictionary add a set of square bracket and inside provide the key name.
>>>dictionary ={"name": "kelvin", age: 23,}
>>>dictionary["name"]
>>>kelvin
NOTE:
When retrieving something from a dictionary make sure you get the spelling well.
Make sure you use the correct data type.
Looping through a dictionary
If you want to iterate the pairs of values in a dictionary you have to use the for-in construct. This is
possible through the use of the items() function.
>>> dict = {"name": kev, "age": 12}
>>> for (key, value) in dict.items():
print(key)
>>> kev
Tuple
It is a data type for immutable ordered sequences of elements. Immutable because you can’t add and remove elements from tuples, or sort them in place.
Sets
Set is a mutable and unordered collection of unique elements. It can permit us to remove duplicate quickly from a list.
Thankyou for reading this article. Hope you learnt something.
Checkout my next article as we go through user defined data structures.
Top comments (0)