List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
output:
['apple', 'banana', 'cherry']
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will
not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the items
will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output:
['apple', 'banana', 'cherry', 'apple', 'cherry']
Python Access List Items
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
output:
banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
output:
cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
output:
['cherry', 'orange', 'kiwi']
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
output:
['apple', 'banana', 'cherry', 'orange']
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
output:
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
output:
['orange', 'kiwi', 'melon']
Updating values in list:
Different ways to update Python List:
Python list provides the following methods to modify the data.
[Link](value) # Append a value
[Link](iterable) # Append a series of values
[Link](index, value) # At index, insert value
[Link](value) # Remove first instance of value
[Link]() # Remove all elements
[Link](value):
If you like to add a single element to the python list then [Link](value) is the best fit for you. The
[Link](value) always adds the value to the end of existing list.
a_list = [1, 2, 3, 4]
a_list.append(5)
print(a_list)
Output:
[1, 2, 3, 4, 5]
[Link](iterable):
The append and extend methods have a similar purpose: to add data to the end of a list. The
difference is that the append method adds a single element to the end of the list, whereas the
extend method appends a series of elements from a collection or iterable.
a_list = [1, 2, 3, 4]
a_list.extend([5, 6, 7])
print(a_list)
Output:
[1, 2, 3, 4, 5, 6, 7]
[Link](index, value):
The insert() method similar to the append() method, however insert method inserts the value at the
given index position, where as append() always add the element at the end of the list.
a_list = [10, 20, 40]
a_list.insert(2, 30 ) # At index 2, insert 30.
print(a_list)
Output:
[10, 20, 30, 40]
If the provided index out of range, then the insert() method adds the new value at the end of the list,
and it inserts the new value to the beginning of the list if the given index is too low.
a_list = [10, 20, 30]
a_list.insert(100, 40)
print(a_list)
a_list.insert(-50, 1)
print(a_list)
Output:
[10, 20, 30, 40]
[1, 10, 20, 30, 40]
[Link](value):
The remove(value) method removes the first occurrence of the given value from the list. There must
be one occurrence of the provided value, otherwise the Python raises ValueError.
a_list = [1, 2, 3, 4, 5, 4]
a_list.remove(4)
print(a_list)
Output:
[1, 2, 3, 5, 4]
Removing min and max values from the list.
a_list = [1, 2, 3, 4, 5, 4, 7, 9 , -1]
a_list.remove(max(a_list)) # removed the max element from the list
a_list.remove(min(a_list)) # removed the min element from the list
print(a_list)
Output:
[1, 2, 3, 4, 5, 4, 7]
[Link]():
The clear() method used to remove all the elements from the list. The same we can also do with del
list[:]
a_list = [10, 20, 30, 40]
a_list.clear()
print(a_list)
Output:
[]
Nested List Comprehensions in Python
List Comprehensions are one of the most amazing features of Python. It is a smart and concise way
of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list
comprehension within another list comprehension which is quite similar to nested for loops.
Let’s take a look at some examples to understand what nested list comprehensions can do:
Example 1:
I want to create a matrix which looks like below:
matrix = [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
The below code uses nested for loops for the given task:
matrix = []
foriinrange(5):
# Append an empty sublist inside the list
[Link]([])
for j inrange(5):
matrix[i].append(j)
print(matrix)
Output:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
The same output can be achieved using nested list comprehension in just one line:
# Nested list comprehension
matrix = [[j for j inrange(5)] foriin range(5)]
print(matrix)
Output:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Explanation:
The syntax of the above program is shown below:
[expression for i in range(5)] –> which means that execute this expression and append its output to
the list until variable i iterates from 0 to 4.
For example:- [i for i in range(5)] –> In this case, the output of the expression
is simply the variable i itself and hence we append its output to the list while i
iterates from 0 to 4.
Thus the output would be –> [0, 1, 2, 3, 4]
But in our case, the expression itself is a list comprehension. Hence we need to first
solve the expression and then append its output to the list.
expression = [j for j in range(5)] –> The output of this expression is same as the
example discussed above.
Hence expression = [0, 1, 2, 3, 4].
Now we just simply append this output until variable i iterates from 0 to 4 which would
be total 5 iterations. Hence the final output would just be a list of the output of the
above expression repeated 5 times.
Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Basic list operations:
The list is a data structuring method that allows storing
the integers or the characters in an order indexed by starting
from 0. List operations are the operations that can be
performed on the data in the list data structure. A few of the
basic list operations used in Python programming are
extend(), insert(), append(), remove(), pop(), slice, reverse(),
min() & max(), concatenate(), count(), multiply(), sort(),
index(), clear(), etc.
List Operations in Python
Some of the most widely used list operations in Python include the following:
1. append()
The append() method adds elements at the end of the list. This method can only add a single
element at a time. You can use the append() method inside a loop to add multiple elements.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link](4)
[Link](5)
[Link](6)
for i in range(7, 9):
[Link](i)
print(myList)
Output:
2. extend()
The extend() method adds more than one element at the end of the list. Although it can add more
than one element, unlike append(), it adds them at the end of the list like append().
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link]([4, 5, 6])
for i in range(7, 11):
[Link](i)
print(myList)
Output:
3. insert()
The insert() method can add an element at a given position in the list. Thus, unlike append(), it can
add elements at any position, but like append(), it can add only one element at a time. This method
takes two arguments. The first argument specifies the position, and the second argument specifies
the element to be inserted.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link](3, 4)
[Link](4, 5)
[Link](5, 6)
print(myList)
Output:
4. remove()
The remove() method removes an element from the list. Only the first occurrence of the same
element is removed in the case of multiple occurrences.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link]('makes learning fun!')
print(myList)
Output:
5. pop()
The method pop() can remove an element from any position in the list. The parameter supplied to
this method is the element index to be removed.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link](3)
print(myList)
Output:
6. slice
The slice operation is used to print a section of the list. The slice operation returns a specific range of
elements. It does not modify the original list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print(myList[:4]) # prints from beginning to end index
print(myList[2:]) # prints from start index to end of list
print(myList[2:4]) # prints from start index to end index
print(myList[:]) # prints from beginning to end of list
Output:
7. reverse()
You can use the reverse() operation to reverse the elements of a list. This method modifies the
original list. We use the slice operation with negative indices to reverse a list without modifying the
original. Specifying negative indices iterates the list from the rear end to the front end of the list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print(myList[::-1]) # does not modify the original list
[Link]() # modifies the original list
print(myList)
Output:
8. len()
The len() method returns the length of the list, i.e., the number of elements in the list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print(len(myList))
Output:
9. min() & max()
The min() method returns the minimum value in the list. The max() method returns the maximum
value in the list. Both methods accept only homogeneous lists, i.e., lists with similar elements.
Code:
myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
print(max(myList))
Output:
10. count()
The function count() returns the number of occurrences of a given element in the list.
Code:
myList = [1, 2, 3, 4, 3, 7, 3, 8, 3]
print([Link](3))
Output:
11. concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is performed
using the + sign. It’s important to note that the individual lists are not modified, and a new combined
list is returned.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)
Output:
12. multiply
Python also allows multiplying the list n times. The resultant list is the original list iterated n times.
Code:
myList = ['EduCBA', 'makes learning fun!']
print(myList*2)
Output:
13. index()
The index() method returns the position of the first occurrence of the given element. It takes two
optional parameters – the beginning index and the end index. These parameters define the start and
end position of the search area on the list. When you supply the begin and end indices, the element
is searched only within the sub-list specified by those indices. When not supplied, the element is
searched in the whole list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print([Link]('EduCBA')) # searches in the whole list
print([Link]('EduCBA', 0, 2)) # searches from 0th to 2nd position
Output:
14. sort()
The sort method sorts the list in ascending order. You can only perform this operation on
homogeneous lists, which means lists with similar elements.
Code:
yourList = [4, 2, 6, 5, 0, 1]
[Link]()
print(yourList)
Output:
15. clear()
This function erases all the elements from the list and empties them.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link]()
Output:
Here the output is empty because it clears all the data.
16. copy()
The copy method returns the shallow copy list. Now the created list points to a different memory
location than the original one. Hence any changes made to the list don’t affect another one.
Syntax:
[Link]()
Code:
even_numbers = [2, 4, 6, 8]
value = even_numbers.copy()
print('Copied List:', value)
Output:
List methods in Python
Python List Methodshas multiple methods to work with Python lists, Below we’ve explained all the
methods you can use with Python lists, for example, append(), copy(), insert(), and more.
List Methods in Python
[Link] Method Description
1 append() Used for appending and adding elements to the end of the List.
2 copy() It returns a shallow copy of a list
[Link] Method Description
3 clear() This method is used for removing all items from the list.
4 count() These methods count the elements
5 extend() Adds each element of the iterable to the end of the List
6 index() Returns the lowest index where the element appears.
7 insert() Inserts a given element at a given index in a list.
8 pop() Removes and returns the last value from the List or the given index value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
11 sort() Sort a List in ascending, descending, or user-defined order
12 min() Calculates the minimum of all the elements of the List
13 max() Calculates the maximum of all the elements of the List
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
output:
('apple', 'banana', 'cherry')
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
output:
banana
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
output:
cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
output:
('cherry', 'orange', 'kiwi')
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
output:
('apple', 'banana', 'cherry', 'orange')
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
output:
('cherry', 'orange', 'kiwi', 'melon', 'mango')
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
output:
('orange', 'kiwi', 'melon')
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
output:
Yes, 'apple' is in the fruits tuple
Updating and deleting elements in tuples:
Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is
created.
But there are some workarounds.
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it
also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list
back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
output:
("apple", "kiwi", "cherry")
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways
to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
output:
('apple', 'banana', 'cherry', 'orange')
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
output:
('apple', 'banana', 'cherry', 'orange')
Note: When creating a tuple with only one item, remember to include a comma after the item,
otherwise it will not be identified as a tuple.
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)
output:
('banana', 'cherry')
Or you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
output:
Traceback (most recent call last):
File "demo_tuple_del.py", line 3, in <module>
print(thistuple) #this will raise an error because the tuple
no longer exists
NameError: name 'thistuple' is not defined
Nested Tuples in Python
A nested tuple is a Python tuple that has been placed inside of another
tuple. Let's have a look at the following 8-element tuple.
1. tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is
known as a nested tuple since it is contained inside another tuple. The
name of the main tuple with the index value, tuple[index], can be used to
obtain the nested tuple, and we can access each item of the nested tuple
by using tuple[index-1][index-2].
Example of a Nested Tuple
Code
1. # Python program to create a nested tuple
2.
3. # Creating a nested tuple of one element only
4. employee = ((10, "Itika", 13000),)
5. print(employee)
6.
7. # Creating a multiple-value nested tuple
8. employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 2
0001), (40, "Peter", 16395))
9. print(employee)
Output:
((10, 'Itika', 13000),)
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40,
'Peter'
Differences between List and Tuple in Python
Sn
o LIST TUPLE
1 Lists are mutable Tuples are immutable
The implication of iterations is Time- The implication of iterations is
2
consuming comparatively Faster
The list is better for performing operations, A Tuple data type is appropriate
3
such as insertion and deletion. for accessing the elements
Tuple consumes less memory as
4 Lists consume more memory
compared to the list
Tuple does not have many built-in
5 Lists have several built-in methods
methods.
Unexpected changes and errors are more
6 In a tuple, it is hard to take place.
likely to occur
Python Dictionaries
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
output:
Ford
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
output:
3
Access Dictionary Items
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
output:
Mustang
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = [Link]("model")
output:
Mustang
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = [Link]()
output:
dict_keys(['brand', 'model', 'year'])
The list of the keys is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
output:
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
x = [Link]()
output:
dict_values(['Ford', 'Mustang', 1964])
The list of the values is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])
Example
Add a new item to the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
x = [Link]()
output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
The returned list is a view of the items of the dictionary, meaning that any
changes done to the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
2020)])
Example
Add a new item to the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964), ('color', 'red')])
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
output:
Yes, 'model' is one of the keys in the thisdict dictionary
update and remove elements
from a Python dictionary
Dictionary update()
The update() method updates the dictionary with the elements from
another dictionary object or from an iterable of key/value pairs.
Example
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
[Link](internal_marks)
print(marks)
# Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}
Example
Insert an item to the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "White"})
print(car)
output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'White'}
Remove items
Several methods are provided by Python to remove items/elements from a
dictionary. They include:
The pop() method:
This is the most common method to remove items from a
dictionary. pop() takes a key as an input and deletes the corresponding
item/element from the Python dictionary. It returns the value associated with
the input key.
The popitem() method:
This method removes and returns a random item key-value from the
dictionary.
The clear() method:
This method drops all the items from the dictionary. clear() is referred to as
the flush method because it flushes everything from the dictionary.
The del method:
Another way to remove an element from a dictionary is to use
the del keyword. del deletes individual elements and eventually the entire
dictionary object.
food_items = {1:"rice", 2:"beans", 3:"yam", 4:"plantain", 5:"potatoes",
6:"wheat"}
# Delete a specific element
print(food_items.pop(6))
print(food_items)
# Delete a random element
print(food_items.popitem())
print(food_items)
# Remove a specific element
del food_items[4]
print(food_items)
# Delete all elements from the dictionary
food_items.clear()
print(food_items)
# Eliminates the whole dictionary object
del food_items
Output
wheat {1: 'rice', 2: 'beans', 3: 'yam', 4: 'plantain', 5: 'potatoes'}
(5, 'potatoes') {1: 'rice', 2: 'beans', 3: 'yam', 4: 'plantain'} {1:
'rice', 2: 'beans', 3: 'yam'} {}
Python Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the k
specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Difference between a List and a Dictionary
The following table shows some differences between a list and a dictionary in Python:
List Dictionary
The list is a collection of index value The dictionary is a hashed structure of the key and value
pairs like that of the array in C++. pairs.
The list is created by placing The dictionary is created by placing elements in { } as
elements in [ ] separated by commas “key”:”value”, each key-value pair is separated by commas
“,” “, “
The indices of the list are integers
The keys of the dictionary can be of any data type.
starting from 0.
The elements are accessed via
The elements are accessed via key-value pairs.
indices.
The order of the elements entered is
There is no guarantee for maintaining order.
maintained.
Lists are orders, mutable, and can Dictionaries are unordered and mutable but they cannot
List Dictionary
contain duplicate values. contain duplicate keys.