Programs

4 Built-in Data Structures in Python: Dictionaries, Lists, Sets, Tuples

In this article, we’ll be focusing on the data structures in Python and help you in understanding the topic clearly. You’ll find out what they are and how they function. We’ve also shared numerous examples to ensure you don’t have any doubts regarding any topics we’ve shared here. 

So, without further ado, let’s get started. 

What are Data Structures?

Data structures let you organize and manage your data effectively and efficiently. They enhance the accessibility of your data. Modifying the stored data becomes quite more straightforward as well if you have suitable data structures in place. They enable you to organize and store the data so you can perform operations on the same later on without facing any kind of difficulties. 

Python has two types of data structures. The data structures Python supports implicitly are Set, Dictionary, List, and Tuple. These are the built-in data structures of Python. 

Then there are data structures you can create yourself to have better control over the functionality. These are user-defined data structures, and they include Linked Lists, Graphs, Trees, Stacks, Queues, and HashMaps. The user-defined data structures are available in other programming languages as well. 

Read more: 6 Most Commonly Used Data Structures in R

Built-in Data Structures in Python

Python has multiple built-in data structures. These integrated data structures help you in solving the programming problems fast and with much ease. As we mentioned earlier, Python has the following integrated data structures:

  • Dictionaries
  • Lists
  • Sets
  • Tuples

Let’s discuss each one of them in detail:

1. Dictionaries

We use dictionaries to store key-value pairs. Just like a physical dictionary has a word stored along with its meaning, a dictionary in Python stores key-value pairs. The terms are the keys, whereas the various meanings associated with those words are the values. With the value, you can access the keys. 

You can create a dictionary with flower braces. You can also use the dict() function for this purpose. Here is an example:

 my_dict = {} #empty dictionary

print(my_dict)

my_dict = {1: ‘A’, 2: ‘B’} #dictionary with elements

print(my_dict)

The output of the above code:

{}

{1: ‘A’, 2: ‘B’}

Our learners also read: Free online python course for beginners!

You can change the values of the dictionary through the keys. You’d have first to access the keys to change the values. Once you’ve located the keys, you just have to add the required key-value pair for getting the desired result. 

 my_dict = {‘First’: ‘A’, ‘Second’: ‘B’}

print(my_dict)

my_dict[‘Second’] = ‘C++’ #changing element

print(my_dict)

my_dict[‘Third’] = ‘Ruby’ #adding key-value pair

print(my_dict)

The output of the above code:

{‘First’: ‘A’, ‘Second’: ‘B’}

{‘First’: ‘A’, ‘Second’: ‘C’}

{‘First’: ‘A’, ‘Second’: ‘C’, ‘Third’: ‘D’}

You can delete the values in your dictionary by using the pop() function. The pop() function returns the value that you had deleted. You can retrieve a key-value pair through the popitem() function. It returns the tuple of the pair. You can clear the whole dictionary as well by using the clear() function. Here’s the example:

 my_dict = {‘First’: ‘A’, ‘Second’: ‘B’’, ‘Third’: ‘C’}

a = my_dict.pop(‘Third’) #pop element

print(‘Value:’, a)

print(‘Dictionary:’, my_dict)

b = my_dict.popitem() #pop the key-value pair

print(‘Key, value pair:’, b)

print(‘Dictionary’, my_dict)

my_dict.clear() #empty dictionary

print(‘n’, my_dict)

The output of the above code:

Value: C

Dictionary: {‘First’: ‘A’, ‘Second’: ‘B’}

Key, value pair: (‘Second’, ‘B’)

Dictionary {‘First’: ‘A’}

{}

Also read: Python Project Ideas and Topics

2. Lists

We use lists to store data sequentially. Every element of the list has an address, which is also called an index. The index value of a list goes from 0 to the last element present in your list, and its name is positive indexing. Similarly, when you go back from the last element to the first one and count from -1, it’s called negative indexing. 

You can create a list by using square brackets and add elements into them as you require. If you leave the brackets empty, the list wouldn’t have any elements, and it would be empty as well. Here’s an example of a list:

 my_list = [] #create empty list

print(my_list)

my_list = [A, B, C, ‘example’, Z] #creating list with data

print(my_list)

The output of the above code:

[]

[A, B, C, ’example’, Z]

You can add elements to your list by using the insert(), extent(), and append() functions. The insert() function adds those elements which were passed to the index value. The insert() function increases the size of the list as well. 

With the append() function, you can add all the elements passed to it as a single element. On the other hand, the extend() function can add the elements one-by-one. 

Here is an example:

 my_list = [A, B, C]

print(my_list)

my_list.append([555, 12]) #add as a single element

print(my_list)

my_list.extend([234, ‘more_example’]) #add as different elements

print(my_list)

my_list.insert(1, ‘insert_example’) #add element i

print(my_list)

Output of the above code:

[A, B, C]

[A, B, C, [555, 12]]

[A, B, C, [555, 12], 234, ‘more_example’]

[A, ‘insert_example’, B, C, [555, 12], 234, ‘more_example’]

While working with lists, you would encounter the need to remove some elements as well. You can use the ‘del’ keyword. It’s a built-in keyword of Python and it doesn’t return anything back. If you want an element back, you’d have to use the pop() function and to remove an element through its value, you’ll have to use the remove() function. Here’s the example:

 my_list = [A, B, C, ‘example’, Z, 10, 30]

del my_list[5] #delete element at index 5

print(my_list)

my_list.remove(‘example’) #remove element with value

print(my_list)

a = my_list.pop(1) #pop element from list

print(‘Popped Element: ‘, a, ‘ List remaining: ‘, my_list)

my_list.clear() #empty the list

print(my_list)

The output of the above code:

[A, B, C, ‘example’, Z, 30]

[A, B, C, Z, 30]

Popped Element: 2 List remaining: [A, C, Z, 30]

[]

You can pass the index values in Python and get the required values. 

 my_list = [A, B, C, ‘example’, Z, 10, 30]

for element in my_list: #access elements one by one

    print(element)

print(my_list) #access all elements

print(my_list[3]) #access index 3 element

print(my_list[0:2]) #access elements from 0 to 1 and exclude 2

print(my_list[::-1]) #access elements in reverse

The output of the above code:

A

B

C

example

Z

10

30

[A, B, C, ‘example’, Z, 10, 30]

example

[A, B]

[30, 10, Z, ‘example’, 3, 2, 1]

Explore our Popular Data Science Courses

3. Sets

A collection of unique and unordered items is called a set. So, if you repeat the data due to some reason, it would appear in the set only once. Sets in Python are similar to the sets you read about in mathematics. From their properties to their functions, you’ll find plenty of similarities among them.

You can create a set by using the flower braces and passing its values. Here’s an example:

 my_set = {A, B, C, D, E, E, E} #create set

print(my_set)

The output of the above code:

{A, B, C, D, E}

Like we mentioned earlier, you can perform all the functions of sets you perform in arithmetics in Python’s sets. With the union() function, you can combine the data present in two sets. The intersection() function gives you the data that’s present in both of the mentioned sets. 

You have the difference() function that lets you delete the data available in both of the sets and gives you the data which isn’t common among them. The symmetric_difference() function gives you the data remaining in those sets. 

 my_set = {A, B, C, D}

my_set_2 = {C, D, E, F}

print(my_set.union(my_set_2), ‘———-‘, my_set | my_set_2)

print(my_set.intersection(my_set_2), ‘———-‘, my_set & my_set_2)

print(my_set.difference(my_set_2), ‘———-‘, my_set – my_set_2)

print(my_set.symmetric_difference(my_set_2), ‘———-‘, my_set ^ my_set_2)

my_set.clear()

print(my_set)

 

The output of the above code:

{A, B, C, D, E, F} ———- {A, B, C, D, E, F}

{C, D} ———- {C, D}

{A, B} ———- {A, B}

{A, B, E, F} ———- {A, B, E, F}

set()

Also read: Python Developer Salary in India

4. Tuples

Tuples are similar to lists, but once you enter data in a tuple, you can’t change it unless it is mutable. Understanding them can be a little tricky, but don’t worry, our example code might help you in that regard. You can create a tuple with the help of the tuple() function. 

 my_tuple = (A, B, C) #create tuple

print(my_tuple)

The output of the above code:

(A, B, C)

The method for accessing values in tuples is the same as in lists. 

 my_tuple2 = (A, B, C, ‘Upgrad’) #access elements

for x in my_tuple2:

    print(x)

print(my_tuple2)

print(my_tuple2[0])

print(my_tuple2[:])

The output of the above code:

A

B

C

Upgrad

(A, B, C, ‘Upgrad’)

A

(A, B, C, ‘Upgrad’)

Read our popular Data Science Articles

Conclusion

Now you must’ve grown familiar with the various data structures in Python. We hope you found this article useful. Data structures play a significant role in helping you with organizing, managing, and accessing your data. There are plenty of options to choose from, and each one of them has its particular uses.

Learn Data Science Courses online at upGrad

If you want to find out more about Python and data structures, you should take a look at our courses. 

If you are curious to learn about python, everything about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

When is the dictionary data type used?

Dictionary can be defined as a valuable data type being used in Python as a collection of data that is stored in the pairs of keys and values. Now, values of the dictionary can be of any data type, but keys have to be an immutable data type like tuple, integer, or string.

Dictionaries are found to be pretty handy when you wish to find a value instantly without going through the entire collection of data. Other than that, a dictionary is also very useful when the order of data is not important. Dictionary data type is preferred when memory consideration is not an important factor because they tend to take up more space as compared to lists and tuples.

What is the difference between lists and tuples?

List and tuples are both sequence data types that are useful for storing the collection of data in Python. The most significant difference between both of them is that lists are mutable, while tuples are immutable. On top of that, the implication of iterations is much faster in tuples as compared to that in lists.

If you wish to perform insertion and deletion operations, then lists make it easy for you. At the same time, elements can be accessed better in tuples. Another important factor that determines the use of any data structure is memory. Here, lists tend to consume more memory as compared to tuples.

How are sets different from lists?

Lists are considered to be the most powerful tool in Python as they don’t always have to be homogeneous. Both lists and sets can contain all sorts of data types. Now, lists can contain duplicate elements, but sets can never contain duplicates, and they will simply disappear from the set.

The order of elements is maintained in lists, but sets can never maintain the order of elements. As lists take up plenty of computational space, they end up taking a huge amount of time. On the other hand, sets make use of hashing for performing look-ups and end up being way faster than lists.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks