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:
>>> groceries[1]
Output:
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:
File “<pyshell#3>”, line 1, in <module>
groceries[2]
IndexError: list index out of range
>>> groceries[-1]
Output:
c. Length in Python
This list has 2 items, milk, and eggs.
>>> len(groceries)
Output:
d. Adding items in Python
We can append an item with the append() method.
>>> groceries.append('bacon') >>> groceries
Output:
We can also extend the list so that it holds more values.
>>> groceries.extend(['ham','bread']) >>> groceries
Output:
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:
>>> 'banana' in groceries
Output:
f. Slicing in Python
If you only want a part of the list, you can slice it with [].
>>> groceries[1:4]
Output:
>>> groceries[-3:-1]
Output:
g. Modifying in Python
Lists are mutable so we can change its items.
>>> groceries
Output:
>>> groceries[2]='cheese' >>> groceries
Output:
h. Deleting in Python
You can use the del keyword to delete items in a list.
>>> del groceries[1] >>> groceries
Output:
>>> groceries.pop()
Output:
>>> groceries.remove('ham') >>> groceries
Output:
i. Looping in Python
You can use a list in a for-loop.
for item in groceries: print(item)
Output:
cheese
j. Concatenating in Python
We can use the + operator to join two lists.
>>> [1,2,3]+[4,5]
Output:
You can also multiply it by an integer to repeat it.
>>> [1,2]*3
Output:
k. Copying in Python
copy() and list() create shallow copies of a list.
>>> groceries.copy()
Output:
>>> list(groceries)
Output:
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:
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:
>>> groceries[1]
Output:
We can also create tuples with the tuple() function.
>>> nums=tuple([1,2,3]) >>> nums
Output:
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:
File “<pyshell#3>”, line 1, in <module>
groceries[2]
IndexError: tuple index out of range
>>> groceries[-1]
Output:
b. Length in Python
This tuple has 2 items too, milk and eggs.
>>> len(groceries)
Output:
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:
>>> 'banana' in groceries
Output:
f. Slicing in Python
If you only want a part of the list, you can slice it with [].
>>> groceries[1:4]
Output:
>>> groceries[:]
Output:
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:
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:
cheese
j. Concatenating tuples in Python
We can use the + operator to join two tuples.
>>> (1,2,3)+(4,5)
Output:
You can also multiply it by an integer to repeat it like in lists.
>>> (1,2)*3
Output:
k. Copying
Tuples do not have the copy() method. You can use the tuple() function to create a tuple.
>>> tuple((1,2,3))
Output:
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:
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:
4. Adding items
You can add items with the add() method.
>>> myset.add(6) >>> myset
Output:
>>> myset.update([7,9]) >>> myset
Output:
5. Deleting items
There are many methods for doing this.
>>> myset={1,2,3,4,5,5,6,7,8,9} >>> myset
Output:
>>> myset.discard(5) >>> myset
Output:
>>> myset.remove(6) >>> myset
Output:
>>> myset.pop()
Output:
>>> myset.clear() >>> myset
Output:
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:
>>> {'a':1, frozenset((1,2,3)):2}
Output:
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:
2. Indexing
You can index dictionaries with keys.
>>> groceries={'milk':25, 'eggs':15} >>> groceries['milk']
Output:
3. Accessing elements
Other than index, you can access elements in this way:
>>> groceries.get('milk')
Output:
4. Adding items
You can add key-value pairs to dictionaries.
>>> groceries['cheese']=30 >>> groceries
Output:
5. Removing items
We can remove items from dictionaries.
>>> groceries={'milk':25, 'eggs':15, 'cheese':20, 'bread':15} >>> groceries.pop('eggs')
Output:
>>> groceries.popitem()
Output:
>>> 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:
eggs 30
cheese 20
bread 15
8. Length and membership
We can get a dictionary’s length.
>>> len(groceries)
Output:
And we can test if a key is in a dictionary.
>>> 'bread' in groceries
Output:
9. Copying
We can create shallow copies of a dictionary.
>>> groceries.copy()
Output:
>>> dict(groceries)
Output:
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:
Python Strings
Python has strings – sequences of characters. We can declare them in single quotes or double-quotes.
>>> 'dog'
Output:
>>> "dog"
Output:
>>> 'dog\'s gone bad'
Output:
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:
>>> text[-5]
Output:
2. Slicing
We can slice strings when we only want a part of them.
>>> text[2:9]
Output:
>>> text[-9:-2]
Output:
>>> text[2::3]
Output:
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:
You can check if a value is in a string.
>>> 'hell' in 'hello'
Output:
5. Length
We can calculate the length of a string with the len() function.
>>> len('hello')
Output:
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.