List, Set, & Dictionary
In this tutorial, you will learn about python data structures and how to use data structure efficiently.
Table of Contents
List:
List in python is a simple, powerful, and one of the most used data structure. Lists are nothing but a collection of data. A list in python allows storing different types of data like String, Integer, Boolean, etc.
Lists are enclosed by [ ] and each item in the list is separated by a comma. The list can have duplicate data and it is ordered collection.
The values of the list can be changes hence the list is mutable.
Create a list:
empids = [100,200,300,400] names =["john","Rick","Albert"] mixed_list = ["physics",1,True]
To check the length of a list:
len(empids)
Access an element from the list:
To access elements from the list, use the index value of that element.
print(empid[0]) # list index in python starts from 0 not 1
An error will be thrown while trying to access an element beyond index:
print(empid[9])
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
Add a new element to the list:
append() method will add the element to the end of the list.
empid.append(500) print(empid)
insert() method allows to insert a new element to any given index.
names.insert(1, "Joe") print(names)
["john","Joe","Rick","Albert"]
Remove an item from the list:
remove() method is used to remove the particular element from the list.
city = ['delhi','mumbai','bangalore', 'chennai'] city.remove('mumbai') print(city)
['delhi', 'bangalore', 'chennai']
del() method is also used to delete an element from the list or delete the entire list.
city = ['delhi','mumbai','bangalore', 'chennai'] del city[1] print(city)
['delhi', 'bangalore', 'chennai']
To delete the entire list use below.
del city
pop() method is used to delete an element using an index. By default pop() method remove the last element from the list if no index is provided.
city = ['delhi','mumbai','bangalore', 'chennai'] city.pop(0) print(city)
['mumbai', 'bangalore', 'chennai']
city.pop() print(city)
['mumbai', 'bangalore']
clear() method is used to clear the list and it will return an empty list.
city.clear() print(city)
[]
Check the length of a list:
To check how many elements present in the list use len() method.
city = ['delhi','mumbai','bangalore', 'chennai'] print(len(city))
4
To copy a list :
city = ['delhi','mumbai','bangalore', 'chennai'] new_city_list = city.copy() print(new_city_list)
['delhi','mumbai','bangalore', 'chennai']
Multi-Dimensional list:
The list can hold multiple dimensional data like below.
cities = ['delhi','mumbai',['bangalore', 'mysore'], 'chennai'] print(cities[2])
['bangalore', 'mysore']
Set:
Set in Python is an unordered collection and does not allow the user to hold duplicate values. Data in a set are enclosed by { } and unlike a list, the set does not have any index.
Create Set:
Sets can be created in multiple ways.
city = {'delhi','mumbai','bangalore', 'chennai'} type(city)
city = set(['delhi','mumbai','bangalore', 'chennai']) type(city)
Access items:
As ‘set’ does not have an index value, we cannot use index value to extract the exact element.
To check if an element presents in a set, use below syntax.
city = set(['delhi','mumbai','bangalore', 'chennai']) print('delhi' in city)
True
or we can use for loop to verify like below:
for item in city: print(item)
Add an element to Set:
add() method is used to add a new element to set.
city = set(['delhi','mumbai','bangalore', 'chennai']) city.add('mysore') print(city)
{'mysore', 'mumbai', 'delhi', 'chennai', 'bangalore'}
update() method is used to add multiple elements to set.
city.update(['newcity1','newcity2']) print(city)
{'newcity1', 'newcity2', 'mumbai', 'delhi', 'chennai', 'bangalore'}
Remove an element:
Use the remove() method to remove an element from a set. This method will throw an error if you are trying to delete an element that does not exist in the set.
city = set(['delhi','mumbai','bangalore', 'chennai']) city.remove('delhi') print(city)
{'chennai', 'mumbai', 'bangalore'}
Now try to delete an element that is not in the set.
city.remove('delhiiii')
Traceback (most recent call last):
File "", line 1, in
KeyError: 'delhiiii'
Use discard() method to delete.This method will not throw any error even if the element does not exist.
city = set(['delhi','mumbai','bangalore', 'chennai']) city.discard('delhi') print(city)
{'chennai', 'mumbai', 'bangalore'}
Now try to delete an element using discard meth which is not in the set.
city.discard('delhiii') print(city)
{'chennai', 'mumbai', 'bangalore'}
Use pop() method to remove an element. pop() method removes the first element of the set.
city.pop()
clear() method is used to clear the entire set.
city.clear()
Delete set:
Use del() to delete set.
city = set(['delhi','mumbai','bangalore', 'chennai']) del city
Dictionary:
Dictionary is python is an unordered and indexed collection. Dictionary is used to store key and value pair. It can not have duplicate keys.
Create Dictionary:
In this example, let’s create a dictionary of employees having the name as key and phone number as value.
phone = { 'john':123987822, 'bob':2347862,' 'rick':1234211 } print(phone)
{'john': 123987822, 'bob': 2347862, 'rick': 1234211}
Access Items:
Items in the dictionary can be accessed by using the key.
print(phone['john'])
123987822
Python returns an error while trying to access using a key that is not available in the dictionary.
print(phone['john1'])
Traceback (most recent call last):
File "", line 1, in
KeyError: 'john1'
get() method is also used to access the element. The only difference is this method will not throw any error if the key does not exist.
phone.get('john')
Update Value:
The value can be changed using a specific key. Let’s say we want to change the phone number of ‘John’.
phone['john'] = 55512345 print(phone)
{'john': 55512345, 'bob': 2347862, 'rick': 1234211}
Add Item:
A new key index is used to add an item to an existing dictionary.
phone = {'john':123987822,'bob':2347862,'rick':1234211} print(phone)
{'john': 123987822, 'bob': 2347862, 'rick': 1234211}
phone['matt'] = 33346577 print(phone)
{'john': 123987822, 'bob': 2347862, 'rick': 1234211, 'matt': 33346577}
Remove Item:
pop() method is used to remove a specific key from the dictionary.
phone.pop('matt') print(phone)
popitem() is used to remove a random element from the dictionary.
phone.popitem()
del() method is used to delete any specific key and delete the entire dictionary.
del phone['john'] print(phone)
clear() method is used to cleat the dictionary.
phone.clear() print(phone)
Find All Keys:
keys() method used to find all keys of a dictionary.
phone = {'john':123987822,'bob':2347862,'rick':1234211} for key in phone.keys(): print(key)
By using list comprehension.
[k for k in phone.keys()]
Conclusion:
In this blog, you learned about python data structures and in the next blog, you will learn List comprehension.