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.

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 in Python

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.

a. Creating List in Python
>>> 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))
b. Indexing in Python

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’
c. Length in Python

This list has 2 items, milk, and eggs.

>>> len(groceries)

Output:

2
d. Adding items in Python

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’]

e. 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
f. Slicing in Python

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’]
g. Modifying in Python

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’]
h. Deleting in Python

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’]
i. Looping in Python

You can use a list in a for-loop.

for item in groceries:
    print(item)

Output:

milk
cheese
j. Concatenating in Python

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]
k. Copying in Python

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

>>> groceries.copy()

Output:

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

Output:

[‘milk’, ‘cheese’]
l. Nested lists and comprehension in Python

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]

Python Tuples

In python data structures, 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 tuples in Python
>>> 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)
a. Indexing in Python

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’
b. Length in Python

This tuple has 2 items too, milk and eggs.

>>> len(groceries)

Output:

2
c. Adding items in Python

Tuples are immutable so we cannot add items to them.

d. Checking membership in Python

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
f. Slicing in Python

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

>>> groceries[1:4]

Output:

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

Output:

(‘milk’, ‘eggs’)
g. Modifying in Python

Tuples are immutable so we cannot modify elements.

h. Deleting tuple in Python

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
i. Looping in Python

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

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

Output:

milk
cheese
j. Concatenating tuples in Python

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)
k. 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)
l. Nested tuples in Python

Tuples can hold tuples.

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

But tuples don’t have tuple comprehension.

Sets and frozensets in Python

In Python data structures, 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 in Python

frozensets are immutable sets. 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}

Python Dictionaries

In python data structures, 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 stringssequences 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.

This was all about python data structures.