As I promised, here I am! I have come again with an in-depth blog post for Python lists and dictionaries. In this blog, we will take a look at the in-built methods for lists and dictionaries provided by python. There are not many complex methods that exist in python. All the in-built methods are very intuitive from name only. So, let's get started!
Lovely Lists Data Type in Python
Python provides several in-built methods with the list. Some of them, you will use on a day-to-day basis but some you might never use. So, let's focus on important ones.
- insert(), append() & extend()
- remove(), pop(), del & clear()
- count(), index() & len()
- sort() & reverse()
- copy()
insert(), append() & extend()
insert()
Syntax: list.insert(position, element)
Insert() method adds an element at the specified position in the list. The element can be any of the in-built data types.
1). Insert string into the list
list1 = ["Python", "Programming"]
str1 = "Learn"
list2 = ["From", "Sahil Fruitwala"]
list1.insert(0, str1)
list1.insert(3, list2)
print(list1)
#OUTPUT: ['Learn', 'Python', 'Programming', ['From', 'Sahil Fruitwala']]
2). Insert number and boolean into the list
list1 = ["Python", "Programming"]
number1 = 13
boolean1 = False
list1.insert(0, number1)
list1.insert(10, boolean1)
print(list1)
# OUTPUT: ['Python', 'Programming', 13, False]
Here, if we add any number more than the ending index data will be added at the end of the list. So, when we did list1.insert(10, boolean1)
, as the list doesn't have ten elements or the 10th index, it will add boolean data at the end of the list.
append()
Syntax: list.append(element)
The append method adds an element at the end of the list. We can use any data type with the append method as well.
list1 = ["Python", "Programming"]
str1 = "Learn"
list2 = ["From", "Sahil Fruitwala"]
list1.append(str1)
list1.append(list2)
print(list1)
# OUTPUT: ['Python', 'Programming', 'Learn', ['From', 'Sahil Fruitwala']]
extend()
Syntax: list.extend(iterable_element)
Extend method adds every element of iterable/sequence (string, list, tuple, set) data type at the end of the list.
list1 = ["Python", "Programming"]
str1 = "Learn"
list2 = ["From", "Sahil Fruitwala"]
tuple1 = ("in", "Python 101")
set1 = {"The", "Blog Series"}
list1.extend(str1)
list1.extend(list2)
list1.extend(tuple1)
list1.extend(set1)
print(list1)
# OUTPUT: ['Python', 'Programming', 'L', 'e', 'a', 'r', 'n', 'From', 'Sahil Fruitwala', 'in', 'Python 101', 'The', 'Blog Series']
remove(), pop(), del & clear()
remove()
Syntax: list.remove(element)
The remove method removes the first instance of a specific element from the list.
list1 = [ 1, 2, 1, 1, 4, 5 ]
list1.remove(1)
print(list1)
# OUTPUT: [2, 1, 1, 4, 5]
If we try to remove the element that does not exist in the list, then python will throw the error.
list1 = [ 1, 2, 1, 1, 4, 5 ]
list1.remove(6)
print(list1)
'''
OUTPUT:
Traceback (most recent call last):
File "C:\\Users\\Sahil\\Desktop\\1.py", line 2, in <module>
list1.remove(6)
ValueError: list.remove(x): x not in list
'''
pop()
Syntax: list.pop()
or list.pop(index)
The pop method by default removes the last element of the list and returns it. We can also pass the specific index to the pop method.
list1 = ["Python", "C++", "Java", "PHP", "Rust"]
pop_element = list1.pop()
print(pop_element)
print(list1)
# OUTPUT: Rust
# OUTPUT: ['Python', 'C++', 'Java', 'PHP']
pop_element = list1.pop(1)
print(pop_element)
print(list1)
# OUTPUT: C++
# OUTPUT: ['Python', 'Java', 'PHP']
del
Syntax: del list[index]
The keyword del removes elements from the specific index in the list. If we use the del
keyword without any index, it will remove the complete variable from the computer's memory.
list1 = ["Python", "C++", "Java", "PHP", "Rust"]
del list1[2]
print(list1)
# OUTPUT: ['Python', 'C++', 'PHP', 'Rust']
list1 = ["Python", "C++", "Java", "PHP", "Rust"]
del list1
clear()
Syntax: list.clear()
The Clear method removes all elements from the list.
list1 = ["Python", "C++", "Java", "PHP", "Rust"]
list1.clear()
print(list1)
# OUTPUT: []
count(), index() & len()
count()
Syntax: list.count(element)
The count method returns the number of occurrences of a specific element in a list.
fruits = ['apple', 'banana', 'cherry', 'mango', 'grape', 'cherry', 'cherry']
num_of_cherry = fruits.count("cherry")
print(num_of_cherry)
# OUTPUT: 3
index()
Syntax: list.index(element)
The index method returns the index of a specific element in the list.
fruits = ['apple', 'banana', 'cherry', 'mango', 'grape', 'cherry', 'cherry']
index_of_cherry = fruits.index("cherry")
print(index_of_cherry)
# OUTPUT: 2
Note: If an element does not exist ion list index() will throw the error.
len()
Syntax: len(list)
Len method returns the length of any sequence datatype and dictionary.
list1 = ['apple', 'banana', 'cherry', 'mango', 'grape', 'cherry', 'cherry']
str1 = "Python Programming"
dict1 = {'lang':"Python", 'Year':2021}
print(len(list1))
print(len(str1))
print(len(dict1))
# OUTPUT: 7
# OUTPUT: 18
# OUTPUT: 2
sort() & reverse()
sort()
Syntax: list.sort()
The sort method sorts all the elements of the list by default into ascending order. We can do the sort operation in descending order by providing the reverse=True argument in the sort function.
nums = [2, 5, 1, 7, 2, 3, 4, 5, 6]
nums.sort()
print(nums)
# OUTPUT: [1, 2, 2, 3, 4, 5, 5, 6, 7]
nums.sort(reverse=True)
print(nums)
# OUTPUT: [7, 6, 5, 5, 4, 3, 2, 2, 1]
The sort method is an in-place method. It means, it does not return any value and does all the operations internally. That is the reason why we have not assigned nums.sort()
to any other value. If we do that we will get the following result.
nums = [2, 5, 1, 7, 2, 3, 4, 5, 6]
new_nums = nums.sort()
print(new_nums)
# OUTPUT: None
reverse()
Syntax: list.reverse()
As the name suggests, the reverse method reverses the whole list. The reverse method is also an in-place method.
nums = [2, 5, 1, 7, 2, 3, 4, 5, 6]
nums.reverse()
print(nums)
# OUTPUT: [6, 5, 4, 3, 2, 7, 1, 5, 2]
copy()
Syntax: list.copy()
There will occur many cases during development when we want to copy the list. The copy method helps us to do that.
num1 = [2, 5, 1, 7, 2, 3, 4, 5, 6]
num2 = num1
num2.reverse()
print(num1)
print(num2)
# OUTPUT:
[6, 5, 4, 3, 2, 7, 1, 5, 2]
[6, 5, 4, 3, 2, 7, 1, 5, 2]
In the general case, num2 will have copied data of num1. But, in the case of the list, it just copies the memory address of num1 to num2. So, whatever changes we make in num2 they all will reflect in num1, and vice versa. So, to copy lists properly we have to use the copy method.
num1 = [2, 5, 1, 7, 2, 3, 4, 5, 6]
num2 = num1.copy()
num2.reverse()
print(num1)
print(num2)
# OUTPUT:
[2, 5, 1, 7, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 7, 1, 5, 2]
Alternatively, you can use the list(list_name)
as well.
num1 = [2, 5, 1, 7, 2, 3, 4, 5, 6]
num2 = list(num1)
num2.reverse()
print(num1)
print(num2)
# OUTPUT:
[2, 5, 1, 7, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 7, 1, 5, 2]
Dope Dictionary Data Type in Python
- clear(), pop() & popitem()
- get(), items() & keys()
- update() & fromkeys()
clear(), pop() & popitem()
clear()
Syntax: dictionary.clear()
The clear() method for the dictionary works the same way it works in the list. This method removes all the elements from a dictionary.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
print(blog)
# OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala', 'year': 2021}
blog.clear()
print(blog)
# OUTPUT: {}
pop()
Syntax: dictionary.pop()
or dictionary.pop(key, default_value)
The pop() method removes and returns the specific element from the dictionary.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
print(blog)
# OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala', 'year': 2021}
year = blog.pop("year")
print(blog) # OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala'}
print(year) # 2021
The pop() is used when we want some default value in case the key does not exist.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
year = blog.pop("years", "NotFound")
print(blog) # OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala', 'year': 2021}
print(year) # NotFound
popitem()
Syntax: dictionary.popitem()
The popitem() removes the last key-value pair from the dictionary and returns as a tuple.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
year = blog.popitem()
print(blog)
# OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala'}
print(year)
# OUTPUT: ('year', 2021)
get(), items(), keys() & values()
get()
Syntax: dictionary.get(keyname)
The get method extracts the value of the specified key
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
year = blog.get("year")
print(year)
# OUTPUT: 2021
items()
Syntax: dictionary.items()
The items method returns the view object of the dictionary. The view object contains all the key-value pairs. One drawback of using the items() method is, that if you make any change in the root or original dictionary it will reflect in the view object variable as well.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
view_object = blog.items()
blog['year'] = 2022
print(view_object)
# OUTPUT: dict_items([('language', 'Python'), ('Blogger', 'Sahil Fruitwala'), ('year', 2022)])
keys() & values()
Syntax: dictionary.keys()
and dictionary.values()
As the name suggests, keys() and values() methods return the view object or keys and values of a given dictionary.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
keys = blog.keys()
print(keys)
# OUTPUT: dict_keys(['language', 'Blogger', 'year'])
values = blog.values()
print(values)
# OUTPUT: dict_values(['Python', 'Sahil Fruitwala', '2022'])
update() & fromkeys()
update()
Syntax: dictionary.get({key:value})
The update method updates the existing key with a specified value and if the key does not exist it adds the new key-value pair.
blog = {
"language": "Python",
"Blogger": "Sahil Fruitwala",
"year": 2021
}
blog.update({"type": "New"})
print(blog)
# OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala', 'year': 2021, 'type': 'New'}
blog.update({"type": "OLD"})
print(blog)
# OUTPUT: {'language': 'Python', 'Blogger': 'Sahil Fruitwala', 'year': 2021, 'type': 'OLD'}
fromkeys()
Syntax: dict.fromkeys(keys, defaultvalue)
When we new parameters from the beginning but are not aware of their values to them, at that time we can create a dictionary with keys and default values.
keys = ( "Python", "Sahil Fruitwala", 2021 )
blog = dict.fromkeys(keys)
print(blog)
# OUTPUT: {'Python': None, 'Sahil Fruitwala': None, 2021: None}
blog1 = dict.fromkeys(keys, "")
print(blog1)
# OUTPUT: {'Python': '', 'Sahil Fruitwala': '', 2021: ''}
Conclusion
Finally! We are at the end of this section 😁.
I know, it is a lot to take in at a time. But, you don't need to remember everything that I have mentioned here. I just showed you so that you can recall what is possible and what is not. There are some other methods as well that I have not mentioned here.
If you want to find out more about the List and Dictionary methods, check out GeeksforGeeks.
That was it!
Make sure to share any thoughts, questions, or concerns. Let me know if you need any help or want to discuss something. Reach out to me on Twitter or LinkedIn. Make sure to share any thoughts, questions, or concerns. I would love to see them.
Thank you for your precious time ❤
If you like this blog you can subscribe to my Newsletter for more amazing content.
Top comments (0)