Python Data Structures – Lists, Tuples, Sets, Dictionaries

Free Python courses with 57 real-time projects - Learn Python

Earlier we have discussed Python Operators. Today, in this Python Data Structures Tutorial, we will talk about different data structures that Python provides us with.

These include Python list, Python tuple, Python set, and Python dictionaries with their syntax and examples.

So, let’s start Python Data Structure.

Python Data Structures - Lists, Tuples, Sets, Dictionaries

Python Data Structures – Lists, Tuples, Sets, Dictionaries

What is Python Data Structures?

You can think of a data structure as a way of organizing and storing data such that we can access and modify it efficiently.

Earlier, we have seen primitive data types like integers, floats, Booleans, and strings. Now, we’ll take a deeper look at the non-primitive Python data structures.

Let’s begin with our first Python Data Structures and lists.

What is Python List?

A list in Python is a heterogeneous container for items. This would remind you of an array in C++, but since Python does not support arrays, we have Python Lists.

1. How to Declare Python List?

To use a list, you must declare it first. Do this using square brackets and separate values with commas.

>>> languages=['C++','Python','Scratch']

You can put any kind of value in a list. This can be a string, a Tuple, a Boolean, or even a list itself.

>>> list1=[1,[2,3],(4,5),False,'No']

Note that here, we put different kinds of values in the list. Hence, a list is (or can be) heterogeneous.

2. How to Access Python List?

a. Accessing an entire list

To access an entire list, all you need to do is to type its name in the shell.

>>> list1

Output

[1, [2, 3], (4, 5), False, ‘No’]
b. Accessing a single item from the list

To get just one item from the list, you must use its index. However, remember that indexing begins at 0. Let’s first take a look at the two kinds of indexing.

  • Positive Indexing– As you can guess, positive indexing begins at 0 for the leftmost/first item, and then traverses right.
>>> list1[3]

Output

False
  • Negative Indexing– Contrary to positive indexing, negative indexing begins at -1 for the rightmost/last item, and then traverses left. To get the same item form list1 by negative indexing, we use the index -2.
>>> type(list1[-2])

Output

<class ‘bool’>

It is also worth noting that the index can’t be a float, it has to be an integer.

>>> list1[1.0]

Output

Traceback (most recent call last):File “<pyshell#219>”, line 1, in <module>list1[1.0]

TypeError: list indices must be integers or slices, not float

If you face any doubt in a Python list or Python Data Structure, please comment.

3. Slicing a Python List

Sometimes, you may not want an entire list or a single item, but a number of items from it. Here, the slicing operator [:] comes into play.

Suppose we want items second through fourth from list ‘list1’. We write the following code for this.

>>> list1[1:4]

Output

[[2, 3], (4, 5), False]

Here, we wanted the items from [2,3] to False. The indices for these boundary items are 1 and 3 respectively. But if the ending index is n, then it prints items till index n-1. Hence, we gave it an ending index of 4 here.

We can use negative indexing in the slicing operator too. Let’s see how.

>>> list1[:-2]

Output

[1, [2, 3], (4, 5)]

Here, -2 is the index for the tuple (4,5).

4. A list is mutable

Mutability is the ability to be mutated, to be changed. A list is mutable, so it is possible to reassign and delete individual items as well.

>>> languages

Output

[‘C++’, ‘Python’, ‘Scratch’]
>>> languages[2]='Java'
>>> languages

Output

[‘C++’, ‘Python’, ‘Java’]

Of how to delete an item, we will see in section d.

5. How to Delete a Python List?

Like anything else in Python, it is possible to delete a list.

To delete an entire list, use the del keyword with the name of the list.

>>> list1

Output

Traceback (most recent call last):File “<pyshell#225>”, line 1, in <module>list1

NameError: name ‘list1’ is not defined

But to delete a single item or a slice, you need its index/indices.

>>> del languages[2]
>>> languages

Output

[‘C++’, ‘Python’]

Let’s delete a slice now.

>>> del languages[1:]
>>> languages

Output

[‘C++’]

6. Reassigning a List in Python

You can either reassign a single item, a slice, or an entire list. Let’s take a new list and then reassign on it.

>>> list1=[1,2,3,4,5,6,7,8]
a. Reassigning a single item
>>> list1[0]=0
>>> list1

Output

[0, 2, 3, 4, 5, 6, 7, 8]
b. Reassigning a slice

Now let’s attempt reassigning a slice.

>>> list1[1:3]=[9,10,11]
>>> list1

Output

[0, 9, 10, 11, 4, 5, 6, 7, 8]
c. Reassigning the entire list

Finally, let’s reassign the entire list.

>>> list1=[0,0,0]
>>> list1

Output

[0, 0, 0]

To get an even deeper look into lists, read our article on Python Lists.

Any query yet on Python Data structures, Please Comment

Python Tuple

This Python Data Structure is like a, like a list in Python, is a heterogeneous container for items.

But the major difference between the two (tuple and list) is that a list is mutable, but a tuple is immutable.

This means that while you can reassign or delete an entire tuple, you cannot do the same to a single item or a slice.

To declare a tuple, we use parentheses.

>>> colors=('Red','Green','Blue')

1. Python Tuple Packing

Python Tuple packing is the term for packing a sequence of values into a tuple without using parentheses.

>>> mytuple=1,2,3,       #Or it could have been mytuple=1,2,3
>>> mytuple

Output

(1, 2, 3)

2. Python Tuple Unpacking

The opposite of tuple packing, unpacking allots the values from a tuple into a sequence of variables.

>>> a,b,c=mytuple
>>> print(a,b,c)

Output

1 2 3

3. Creating a tuple with a single item

Let’s do this once again. Create a tuple and assign a 1 to it.

>>> a=(1)

Now, let’s call the type() function on it.

>>> type(a)

Output

<class ‘int’>

As you can see, this declared an integer, not a tuple.

To get around this, you need to append a comma to the end of the first item 1. This tells the interpreter that it’s a tuple.

>>> a=(1,)
>>> type(a)

Output

<class ‘tuple’>

4. Accessing, Reassigning, and Deleting Items

We can perform these operations on a tuple just like we can on a list. The only differences that exist are because a tuple is immutable, so you can’t mess with a single item or a slice.

>>> del a[0]

Output

Traceback (most recent call last):File “<pyshell#251>”, line 1, in <module>del a[0]

TypeError: ‘tuple’ object doesn’t support item deletion

Even though this tuple has only one item, we couldn’t delete it because we used its index to delete.

Python Set

This is one of the important Python Data Structures. A Python set is a slightly different concept from a list or a tuple. A set, in Python, is just like the mathematical set. It does not hold duplicate values and is unordered. However, it is not immutable, unlike a tuple.

Let’s first declare a set. Use curly braces for the same.

>>> myset={3,1,2}
>>> myset

Output

{1, 2, 3}

As you can see, it rearranged the elements in an ascending order.

Since a set is unordered, there is no way we can use indexing to access or delete its elements. Then, to perform operations on it, Python provides us with a list of functions and methods like discard(), pop(), clear(), remove(), add(), and more. Functions like len() and max() also apply on sets.

Any Doubt yet in Python Data Structures? Please Comment.

Python Dictionaries

Finally, we will take a look at Python dictionaries. Think of a real-life dictionary. What is it used for? It holds word-meaning pairs. Likewise, a Python dictionary holds key-value pairs. However, you may not use an unhashable item as a key.

To declare a Python dictionary, we use curly braces. But since it has key-value pairs instead of single values, this differentiates a dictionary from a set.

>>> mydict={1:2,2:4,3:6}
>>> mydict

Output

{1: 2, 2: 4, 3: 6}

To access pairs from a Python dictionary, we use their keys as indices. For example, let’s try accessing the value 4.

>>> mydict[2]

Output

4

This was all about the Python Data Structures Tutorial.

Python Interview Questions on Data Structures

  1. Is Python good for data structures?
  2. What are the different types of data structures in Python?
  3. What is Python Data Structure? Explain with example.
  4. What is set data structure in Python?
  5. What data structure is Python list?

Conclusion

Summing up for today’s Python Data Structures tutorial, we learned about various user-defined data structures using python like lists, tuples, sets, and dictionaries.

All of these have their own advantages and disadvantages. It is highly recommended to refer to our tutorials on each of those to sharpen your axes. See you later.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

14 Responses

  1. paba says:

    Your step by step coverage on topics is really helpful. Thanks for creating this stuff.

    • DataFlair Team says:

      We are glad that our readers are liking DataFlair articles. Keep visiting the DataFlair website for more such learnings.

  2. raj says:

    in set its immutable

  3. sruthi says:

    e. Reassigning a List in Python –> 2. Reassigning a slice -> list1[1:3]=[9,10,11]

    Isn’t it “list1[1:4]=[9,10,11]” ??

    • DataFlair Team says:

      Hello Sruthi,
      We reassign the slice list1[1:3] with this list [9,10,11]. So it scrapes the elements 2 and 3, and puts 9, 10, and 11 in their place. They don’t have to be the same size.
      Hope, it helps!

  4. muhammad Aqib says:

    it was very beneficial for me …thx

  5. Bhukya pravallika says:

    Can u please tell me …….in sets key for dictionary is possible or impossible? In lists it is not possible and for tuple it is possible when only immutable elements are stored then what about set?

    • DataFlair says:

      set does not hold duplicate values and is unordered. So you can store the keys of ductionary in a set beacuse keys are also unique.

  6. Anna Lilliman says:

    I only have one question…why?

    What was wrong with just one. Why do we need all 4? What are the advantages of each one that make them useful…

    All the best,
    Anna L.

    • DataFlair Team says:

      “Hi Anna
      Could you please provide a clear and concise explanation of what you are unsure about?”

  7. ANYANWU THEODORE says:

    your explanation in python is perfect but will like to learn more .how can i get your tutorial .
    Please, you can reach me through my email.

  8. maxtima Bah says:

    After completing this course, I am sure that I will be in a position to call myself software developer, because this course has all it takes to master Python Language.

Leave a Reply

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