Python Data Structures – Learn to choose data structures wisely

Python is dynamically typed and you don’t have to declare data type when declaring a variable. But Python has many data structures – collections of data, for different purposes. In this tutorial, we will discuss different types of Python data structures in brief.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Python Data Structure?

Python has primary data types like Boolean, int, float, and complex. It also has data structures to store collections of values. The data structures in Python are lists, tuple, dictionaries, sets, and strings. Some of them are mutable and the others are immutable.

  • Lists
  • Tuples
  • Sets and frozensets
  • Dictionaries
  • Strings

Let’s discuss the types of data structures in detail.

Types of Python Data Structures

1. Lists

Python does not have arrays but it has lists. Lists are ordered collections of items, they are mutable and heterogeneous. Let’s take an example.

1.1 Creating

>>> groceries=['milk','eggs']

This list is called groceries and it has milk and eggs. Let’s see how we will access these values.

>>> groceries[0]

Output:

‘milk’
>>> groceries[1]

Output:

‘eggs’

We can also create lists with the list() function.

>>> nums=list()
>>> nums.append(4)
>>> nums1=[]
>>> nums1.append(5)
>>> nums2=list((1,2,3,4))

1.2. Indexing

We access them by indexing. Indexing starts at 0. ‘milk’ has index 0, not 1. And ‘eggs’ has index 1, not 2.

Index 2 does not exist, so trying to access it gives us an IndexError.

>>> groceries[2]

Output:

Traceback (most recent call last):
  File “<pyshell#3>”, line 1, in <module>
    groceries[2]
IndexError: list index out of range
>>> groceries[-1]

Output:

‘eggs’

1.3. Length

This list has 2 items, milk, and eggs.

>>> len(groceries)

Output:

2

1.4. Adding items

We can append an item with the append() method.

>>> groceries.append('bacon')
>>> groceries

Output:

[‘milk’, ‘eggs’, ‘bacon’]

We can also extend the list so that it holds more values.

>>> groceries.extend(['ham','bread'])
>>> groceries

Output:

[‘milk’, ‘eggs’, ‘bacon’, ‘ham’, ‘bread’]

1.5. Checking membership

We can check whether an item exists in the list. We use the ‘in’ and ‘not in’ operators.

>>> 'eggs' in groceries

Output:

True
>>> 'banana' in groceries

Output:

False

1.6. Slicing

If you only want a part of the list, you can slice it with [].

>>> groceries[1:4]

Output:

[‘eggs’, ‘bacon’, ‘ham’]
>>> groceries[-3:-1]

Output:

[‘bacon’, ‘ham’]

1.7. Modifying

Lists are mutable so we can change its items.

>>> groceries

Output:

[‘milk’, ‘eggs’, ‘bacon’, ‘ham’, ‘bread’]
>>> groceries[2]='cheese'
>>> groceries

Output:

[‘milk’, ‘eggs’, ‘cheese’, ‘ham’, ‘bread’]

1.8. Deleting

You can use the del keyword to delete items in a list.

>>> del groceries[1]
>>> groceries

Output:

[‘milk’, ‘cheese’, ‘ham’, ‘bread’]
>>> groceries.pop()

Output:

‘bread’
>>> groceries.remove('ham')
>>> groceries

Output:

[‘milk’, ‘cheese’]

1.9. Looping

You can use a list in a for-loop.

for item in groceries:
    print(item)

Output:

milk
cheese

1.10. Concatenating

We can use the + operator to join two lists.

>>> [1,2,3]+[4,5]

Output:

[1, 2, 3, 4, 5]

You can also multiply it by an integer to repeat it.

>>> [1,2]*3

Output:

[1, 2, 1, 2, 1, 2]

1.11. Copying

copy() and list() create shallow copies of a list.

>>> groceries.copy()

Output:

[‘milk’, ‘cheese’]
>>> list(groceries)

Output:

[‘milk’, ‘cheese’]

1.12. Nested lists and comprehension

You can make a list hold another list.

>>> nums=[1,2,[3,4],5]

You can also define it quickly.

>>> nums=[num for num in range(7)]
>>> nums

Output:

[0, 1, 2, 3, 4, 5, 6]

Any doubts in Python data structures article till now? Mention them in the comment section. TechVidvan’s team will be happy to help you.

Python Tuples

Tuples are like lists, ordered collections of items. They can be heterogeneous but they are immutable. This means you cannot change their values. Let’s take an example.

1. Creating

>>> groceries=('milk','eggs')

This tuple is called groceries and it has milk and eggs. Let’s see how we will access these values.

>>> groceries[0]

Output:

‘milk’
>>> groceries[1]

Output:

‘eggs’

We can also create tuples with the tuple() function.

>>> nums=tuple([1,2,3])
>>> nums

Output:

(1, 2, 3)

1.1. Indexing

Like lists, we access them by indexing. Indexing starts at 0. ‘milk’ has index 0 and ‘eggs’ has index 1.

Index 2 does not exist, so trying to access it gives us an IndexError.

>>> groceries[2]

Output:

Traceback (most recent call last):
  File “<pyshell#3>”, line 1, in <module>
    groceries[2]
IndexError: tuple index out of range
>>> groceries[-1]

Output:

‘eggs’

1.2. Length

This tuple has 2 items too, milk and eggs.

>>> len(groceries)

Output:

2

1.3. Adding items

Tuples are immutable so we cannot add items to them.

1.4. Checking membership

We can check whether an item exists in a tuple. We use the ‘in’ and ‘not in’ operators here as well.

>>> 'eggs' in groceries

Output:

True
>>> 'banana' in groceries

Output:

False

1.5. Slicing

If you only want a part of the list, you can slice it with [].

>>> groceries[1:4]

Output:

(‘eggs’,)
>>> groceries[:]

Output:

(‘milk’, ‘eggs’)

1.6. Modifying

Tuples are immutable so we cannot modify elements.

1.7. Deleting

You can delete a complete tuple but you cannot delete elements from it.

>>> del groceries[1]

Output:

Traceback (most recent call last):
  File “<pyshell#50>”, line 1, in <module>
    del groceries[1]
TypeError: ‘tuple’ object doesn’t support item deletion

1.8. Looping

You can use a tuple as well in a for-loop.

>>> for item in groceries:
  print(item)

Output:

milk
cheese

1.9. Concatenating

We can use the + operator to join two tuples.

>>> (1,2,3)+(4,5)

Output:

(1, 2, 3, 4, 5)

You can also multiply it by an integer to repeat it like in lists.

>>> (1,2)*3

Output:

(1, 2, 1, 2, 1, 2)

1.10. Copying

Tuples do not have the copy() method. You can use the tuple() function to create a tuple.

>>> tuple((1,2,3))

Output:

(1, 2, 3)

1.11. Nested tuples

Tuples can hold tuples.

>>> nums=(1,2,(3,4),5)

But tuples don’t have tuple comprehension.

Next in the Python data structures article, we will see sets and frozensets in Python.

Sets and frozensets

Sets are collections of values and are unordered, heterogeneous, not indexed and do not hold duplicate elements.

1. Creating

You can create a set with curly braces {} and separating elements with commas. This is a set:

>>> myset={1, 2.0, False}

>>> set([1, 2.0])

Output:

{1, 2.0}

You can also use the set() function.

2. Indexing

You cannot index or slice sets.

3. Length

You can get a set’s length with the len() function.

>>> len(myset)

Output:

3

4. Adding items

You can add items with the add() method.

>>> myset.add(6)
>>> myset

Output:

{False, 1, 2.0, 6}
>>> myset.update([7,9])
>>> myset

Output:

{False, 1, 2.0, 6, 7, 9}

5. Deleting items

There are many methods for doing this.

>>> myset={1,2,3,4,5,5,6,7,8,9}
>>> myset

Output:

{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> myset.discard(5)
>>> myset

Output:

{1, 2, 3, 4, 6, 7, 8, 9}
>>> myset.remove(6)
>>> myset

Output:

{1, 2, 3, 4, 7, 8, 9}
>>> myset.pop()

Output:

1
>>> myset.clear()
>>> myset

Output:

set()

You can perform operations on sets like union, intersection and set-difference. We will discuss them later.

frozenset

frozensets are immutable sets. And so they can be used as keys for dictionaries- regular sets can’t be used.

>>> frozenset((1,2,3))

Output:

frozenset({1, 2, 3})
>>> {'a':1, frozenset((1,2,3)):2}

Output:

{‘a’: 1, frozenset({1, 2, 3}): 2}

Now, in Python data structures article let’s discuss what is dictionaries in Python. 

Python Dictionaries

Dictionaries are unordered mutable and indexed collections of items. Dictionaries have key-value pairs. They are created in curly braces. Dictionary keys are unique and immutable.

1. Creating

You can create a dictionary with curly braces and separating keys and values by colons and key-value pairs by commas.

>>> groceries={'milk':25, 'eggs':15}

You can also use the dict() function to create a dictionary.

>>> groceries=dict([(1,2),(3,4)])
>>> groceries

Output:

{1: 2, 3: 4}

2. Indexing

You can index dictionaries with keys.

>>> groceries={'milk':25, 'eggs':15}
>>> groceries['milk']

Output:

25

3. Accessing elements

Other than index, you can access elements in this way:

>>> groceries.get('milk')

Output:

25

4. Adding items

You can add key-value pairs to dictionaries.

>>> groceries['cheese']=30
>>> groceries

Output:

{‘milk’: 25, ‘eggs’: 15, ‘cheese’: 30}

5. Removing items

We can remove items from dictionaries.

>>> groceries={'milk':25, 'eggs':15, 'cheese':20, 'bread':15}
>>> groceries.pop('eggs')

Output:

15
>>> groceries.popitem()

Output:

(‘bread’, 15)
>>> del groceries['cheese']
>>> groceries.clear()
>>> groceries

Output:

{}

6. Changing values

We can change values in a dictionary.

>>> groceries={'milk':25, 'eggs':15, 'cheese':20, 'bread':15}
>>> groceries['eggs']=30

7. Looping

We can loop on dictionaries with a for-loop.

for key,value in groceries.items():
    print(key,value)

Output:

milk 25
eggs 30
cheese 20
bread 15

8. Length and membership

We can get a dictionary’s length.

>>> len(groceries)

Output:

4

And we can test if a key is in a dictionary.

>>> 'bread' in groceries

Output:

True

9. Copying

We can create shallow copies of a dictionary.

>>> groceries.copy()

Output:

{‘milk’: 25, ‘eggs’: 30, ‘cheese’: 20, ‘bread’: 15}
>>> dict(groceries)

Output:

{‘milk’: 25, ‘eggs’: 30, ‘cheese’: 20, ‘bread’: 15}

10. Nested dictionaries and comprehension

Dictionaries can contain dictionaries as values but not as keys.

>>> dict1={'a': {'a':1, 'b':2}, 'c':3}

We can also create dictionaries by comprehension.

>>> {num:num**2 for num in range(6)}

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Python Strings

Python has strings – sequences of characters. We can declare them in single quotes or double-quotes.

>>> 'dog'

Output:

‘dog’
>>> "dog"

Output:

‘dog’
>>> 'dog\'s gone bad'

Output:

“dog’s gone bad”

When we want to include quotes in a string surrounded by the same quotes, we can use escape characters.

1. Indexing

We can index strings too.

1.1. Positive indexing:

>>> text='I had a bad day today'
>>> text[6]

Output:

‘a’
>>> text[-5]

Output:

‘t’

2. Slicing

We can slice strings when we only want a part of them.

>>> text[2:9]

Output:

‘had a b’
>>> text[-9:-2]

Output:

‘day tod’
>>> text[2::3]

Output:

‘h b yoy’

3. Deleting

We can delete complete strings but not a character or a slice.

>>> del text
>>>

4. Concatenation and membership

We can join two strings with the + operator.

>>> 'hello'+'world'

Output:

‘helloworld’

You can check if a value is in a string.

>>> 'hell' in 'hello'

Output:

True

5. Length

We can calculate the length of a string with the len() function.

>>> len('hello')

Output:

5

We can also format strings with the % operator, f-strings and the format() method.

Summary

In TechVidvan’s Python data structures article, we learned about data structures, lists, tuples, sets and frozensets, dictionaries and strings. These are the various types of data structures in Python. We can use them to store collections of values.

If you find this Python data structures article helpful, do rate us on Google.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.