DEV Community

Alvinimbua
Alvinimbua

Posted on

Deep dive into Data Structures & Algorithms.

In this article, we will discuss about the data structures and algorithms in the Python programming language. The common data structures in python include:

  • Lists
  • Sets
  • Tuples
  • Dictionaries

Lists

A list is used to store one or more python objects or data types. Lists are commonly enclosed within square brackets([]) and elements are comma separated. List has some methods which include list.append(x),list.insert(i,x),list.remove(x), list.count(x), list.index(x) just but to mention a few.
Below is an example of list.

>>> months = ['January', 'February', 'July', 'June']
>>> months.count('July')
3
>>>months.index('February')
1
Enter fullscreen mode Exit fullscreen mode

Also one thing to note is that Lists are mutable.

Sets

It is a type of data structure that contains a collection of unique elements. It uses hash to improve performance. Indexing is not supported in this of data structure. It is also mutable, meaning it can be changed once declared. Are denoted by the use of curly brackets({}). N/B To create an empty set you have to use set() and not {}, since the latter will create a dictionary.

>>> days = {'monday', 'tuesday', 'wedenesday', 'thursday', 'monday'}
>>> print (days)
{'monday', 'tuesday', 'wedenesday', 'thursday'} # duplicates have been removed
Enter fullscreen mode Exit fullscreen mode

Tuples

A tuple built in data structure that contains ordered collection of objects.They come with a limited functionality than lists.
The distinguishing part between tuple and list the mutability aspect in that, tuple are immutable i.e they can not be changed once declared, while list are mutable. They are denoted using parenthesis(), and are separated by comma.
AN example of a tuple is :

tuple = (item 1, item2, item3).
_
Application of tuple._
-Tuples are used the user does not want to modify data.
-When you want use less memory and execute program faster.

Dictionaries

Also a built in data structure, sometimes referred to other languages as associative arrays or associative memories. Dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
They are always denoted as key:pair value. Dictionaries are mutable, in that you can insert or delete entries in them. While deleting an item in the dictionary, you use the "del" keyword.
Illustration

>>> tel = {'alvin': 4098, 'stela': 4139}
>>> tel['moreen'] = 4127
>>> tel
{'alvin': 4098, 'stela': 4139, 'moreen': 4127}
Enter fullscreen mode Exit fullscreen mode

To learn more about data structures in python, kindly refer here

Top comments (0)