Python — Lists and Dictionaries
Congratulation 🎉 🎉 🎉 Today we will discuss Lists and Dictionaries in Python. If you haven’t read the variables section, I suggest you read it first. You can access the previous section from the link above.
Python provides Lists and Dictionaries to storing data like array or JSON in Javascript. Lists are identical to arrays. An array can store just a single data type in Python, but a list can do more. We can store various data types in a single list.
List
From the following example, we declare a new list with the list’s name and assign it with brackets :
list_name = [data1, data2, data3]
Basic Operations with List
You can do some basic operations with lists like concatenation, repetition, and iteration.
Built-in Function and Method
There are some built-in functions and methods we can do to list. The following functions are :
- len(list_name) ➡️ return length of list.
- max(list_name) ➡️ return max value from list.
- min(list_name) ➡️ return min value from list.
The following list methods:
- list_name.append(object) ➡️ add data to the end of list index.
- list_name.count(object) ➡️ count object in current list.
- list_name.extend(seq) ➡️ append sequence to list.
- list_name.index(object) ➡️ return index of specified object in list.
- list_name.insert(index, object) ➡️ insert an object or data to specified index.
- list_name.pop(object=list_name[-1]) ➡️ remove and return the last popped object in list.
- list_name.remove(object) ➡️ remove specified object from list.
- list_name.reverse() ➡️ reverse object of list in place.
- list_name.sort([function]) ➡️ sort object of list, use compare function if given.
Dictionary
Dictionary stores data with key and value like a conventional dictionary in our school 😄 The form of the dictionary is the same as JSON in Javascript.
If you want to delete any key and value of the dictionary, you can use the following method:
Built-in Function
There is some built-in function that we can use to work with dictionaries.
- dict.clear() ➡️ Remove all key and value of the dictionary.
- dict.copy() ➡️ Return a shadow of copy from a dictionary.
- dict.get(key, Default=None) ➡️ Return value of dictionary by given key
- dict.update(dict2) ➡️ Update dictionary with key-pairs of dict2.