Understanding Python: Part 3
Last Updated on September 25, 2020 by Editorial Team
Author(s): Suhas V S
Programming
All you need to know about the very interesting βData Structuresβ in python programming.
βPython Collectionβ also called βPython Data Structureβ constitutes the core functionality of how data is stored and being assigned to a variable. All the examples we have seen until now in this series βUnderstanding Pythonβ had one element assigned to a variable and the data type of the element was either an int, float, or a bool. Moving forward in this article, we will be focussing more on the βadvanced data typesβ(list, tuple, set, and dictionary) wherein a variable can hold more than oneΒ element.
Python Collections
- List
- Tuple
- Dictionary
- Set
We will be learning about each item in the contents for their accessing technique, properties, operations, and the methods theyΒ offer.
1.List
1.1) What is aΒ βlistβ?
The list is a collection in python that can hold multiple elements in it of different data types. It is denoted by square brackets[] and separate items in it with commas. A simple example is an empty list where an object is created as soon as you instantiate it by assigning it to a variable.
Now, let us see how we can have a list with multiple elements from different data types. In Figure[2], we have a list βaβ that has elements of int(1,2,3,4), of string(βPythonβ), of float(45.67), and bool (True) data types inΒ it.
Also, a list can hold another list inside it. It is called the βNested listβ. Figure[3] shows how my_list variable holds 2 lists [βPyhtonβ,βis Funβ] and [23,45,67]
1.2) Accessing elements in aΒ list
Each element in the list is assigned with an index number and you can access the list items by referring to the index number. The index starts from β0β(from left to right). The first element has an index β0β and the last element has an index number βnumber of elements in the list -1β(since the index starts from 0). Every index is an integer and it helps us to just access any element with its integer indexΒ value.
There are 2 ways in which you can access an element in the list. The first way is with positive indexing and the second way is with negative indexing. Let us take the example shown in Figure[2] and understand both techniques.
Here in the Figure[4], I have shown how an element is indexed in βpositive indexingβ(starts from β0β ), and in the case of βnegative indexingβ, the last element(from left) is assigned with -1. Now, let us see a few questions and put this concept into practice.
Hint: Refer to the table in Figure[4] and note down the index values from the positive indexing technique and as well as from the negative indexing technique. To get/retrieve the respective elements, just put the index value inside the square bracket after the variable name.(for example a[2] retrives the 3rd element from the listΒ βaβ).
Consider the list βaβ in Figure[2].
Q 1) Print the first element in the list βaβΒ ?(Use both the accessing techniques)
Q 2) Print the last element in the list βaβΒ ?(Use both the accessing techniques)
Q 3) Print the element βPythonβ from the list βaβΒ ?(Use both the accessing techniques)
I am sure after seeing the above 3 questions, you would be confident in the access techniques used to extract or retrieve a certainΒ element.
1.3) Slicing elements in aΒ list
To print a part of the list by selecting some elements, we use a slice operator (:) between the start and the end index values. Here, the index value on the left of the operator includes the element in its position in the sliced list whereas, the index value on the right of the operator excludes the element at the end index value. It considers the element before the element at the end index value. I know it seems a bit confusing to read through all this. Hence, refer to Figure[8] for a better understanding.
Consider the list βaβ in Figure[2], let us put our learning on list slicing into practice by taking a few questions.
Hint: Again refer to the indexing table in Figure[4] for the index values and put them in the format shown in the figure[8].
Q 1) Print/Slice the first 3 elements in the list βaβ(Use both the accessing techniques).
Q 2) Print/Slice all the elements from 4 toΒ True.
Q 3) Print all the elements of the list without using indexΒ values.
Q 4) Reverse the list elements using a negative indexing technique.
With these practice questions, I hope the concepts of accessing and slicing list areΒ clear.
NOTE: Accessing and Slicing techniques shown for lists are the same for Strings and Tuples. Hence, it very a important concept to understand and practice.
1.4) Mutability ofΒ Lists
We can change/delete the elements of the list after we have created it. This is what makes list mutable. Let us see how we can realize with an example each. Refer to Figure[13].
General Properties of list: It is an ordered, indexed,heterogenous and mutable python collection. It can also hold duplicate elements.
1.5) Common βlistβ operations
There are 2 common list operations that we can perform on a list. They are, concatenation(+) and repetition(*). Let us understand with an example forΒ each.
Concatenation(+):
The β+β operator is used to combine(concatenate) two or more lists. Figure[14] shows how 2 lists βcourse1β and βcourse2β are concatenated using the β+β operator.
Repetition(*):
The β*β operator is used to repeat a list βnβ number of times. The βnβ is specified by the user and has to be positive.
1.6) ListΒ Methods
The list collection has a wide range of methods to make the operations easier and flexible. We will see how to check for all the available methods and understand theirΒ working.
It is a whole lot easier to learn methods while working with βJupyterβ as it lets you research for available methods in just a line. i.e dir(list). After running it, the output is a list of all the available methods in python for a certain version. Refer to Figure[16] and you will find all the list methods starting from βappendβ toΒ βsortβ.
Here is a brief description of what each of the built-in list methodsΒ does.
Let us some examples and understand how these methods are realized. I have commented appropriately as these are self-explanatory.
append andΒ extend:
The method list.append(element) will add the element at the end of a list. It can only add one element to the list. To add more elements, we use the method βextendβ.
clear:
The clear method resets the list to an emptyΒ state.
copy:
This method returns a shallow copy of the list. That means it does not create a new object for the copied list instead it creates a reference to the copiedΒ list.
Consider the example in Figure[20]. βnew_listβ is assigned with a shallow copy of the list βListβ. Here, upon adding a new element βpigβ, only the original list βListβ will be updated not the one which is shallowly copied(new_list).
count:
It returns the number of occurrences of the specified object in theΒ list.
index:
It returns the lowest index in the list that the objectΒ appears.
insert:
The object is inserted into the list at the specified index.
pop:
It removes and returns the last object of theΒ list.
remove:
It removes the specified object from theΒ list.
reverse:
It reverses theΒ list.
sort:
It sorts the list in ascending order.
1.7) Some common built-in functions that work on the list( also works with set,Β tuple)
len:
This function returns the size of aΒ list.
sum:
It adds all the elements in the list and returns an aggregated sum value. It only works when all the elements are either int orΒ float.
min andΒ max:
They return the smallest and largest element in the list. Again, it only works when all the elements are either int orΒ float.
Note: If you are stuck to know what a function or a method does, just type the help( function_name) and you will be able to see the description. If the method belongs to a certain class then, you have to include as help(class.method_name). For example, help(list.clear) gives the method description of βclearβ method of the classΒ βlistβ.
2. Tuple
2.1) What is aΒ βTupleβ?
It is another python collection of elements where the elements are separated by commas inside round brackets ( ). Let us see how we can create different tuples in the following Figure[27].
2.2) Accessing and Slicing aΒ tuple
The techniques used to access and slice a list is exactly used for tuple as well. Please refer to 1.2 & 1.3 parts of this article for moreΒ details.
2.3) Mutability in aΒ tuple
Tuples are immutable, unlike lists. They can not be modified after their creation. However, we can change the elements of nested items in a tuple that are mutable. Refer Figure[28] and Figure[29] for a better understanding.
The deletion of an element of a tuple is not possible. However, deleting the entire tuple is possible.
General properties of a Tuple: It is indexed,ordered,immutable and heterogenous.
2.4) Tulple built-inΒ methods
We have 2 python built-in methods for the tuple. Both are covered in the list. Let us see how they work over aΒ tuple.
count:
It returns the number of times a specified element occurs in aΒ tuple.
index:
It searches the tuple for the first occurrence of a specified element and returns the index value for that particular position.
3. Dictionary
3.1) What is a βDictionaryβ?
Python dictionary is an unordered collection of elements. It maps keys to values and these key-value pairs provide a useful way to store data in python. Separate the keys from values with a colon(:), and a pair from another by a comma(,). Put it all in curly braces{ } as shown in Figure[32].
In the above figure βRohitβ, βViratβ and βShikharβ are the keys, and 145,78,56 are their respective values.
3.2) Accessing values in a dictionary
Use the key inside the square brackets to access the elements from a dictionary. Also, you can use the get() method which we will see in dictionary methods.
3.3) Mutability in a dictionary
Once a dictionary is created, only the values in it can be modified not the keys. Hence, keys are immutable and values areΒ mutable.
Add an item to the dictionary by using a new index key and assign a value toΒ it.
3.4) Built-in Methods in the dictionary
Figure[37] shows the available built-in dictionary methods. Let us see an example for each and understand.
dict.clear():
It is used to delete all the items of the dictionary.
dict.copy():
It returns a shallow copy of the dictionary.
dict.fromkeys():
Create a new dictionary from the iterable(list or tuple)with the values equal toΒ value.
dict.get(key):
It is used to get the value specified for the passedΒ key.
dict.items():
It returns all the key-value pairs as aΒ tuple.
dict.keys():
It returns all the keys of the dictionary.
dict.setdefault():
It is used to set the key to the default value if the key is not specified in the dictionary.
dict.update():
It updates the dictionary by adding the key-value pair of another dictionary to this dictionary.
dict.values():
It returns all the values of the dictionary
Note: Each key should be unique. If you ever try to create a dictionary with duplicate keys, the last value of the key will be retained and the first value will be excluded. Refer to Figure[47].
4. Set
4.1) What is aΒ βsetβ?
The set is a collection of unique and unordered elements. It is denoted by { } with comma-separated elements inside the curly brackets. It also holds elements from other data types which makes it heterogeneous. The set is a mutable collection where the elements are not indexed, hence they can not be accessed. Let us now see some examples of creating a set in Figure[48].
4.2) Set built-in functions
To get all the available methods that are in sets, just type dir(set) and it lists all the available methods. Let us see some of them with anΒ example.
add andΒ update:
The βaddβ method is used to add an element to an existing set whereas the βupdateβ method is used to add more than one element to an existing set. Figure[49] shows the difference between the add and the updateΒ method.
remove:
It removes an element specified by theΒ user.
pop:
It removes a random element from the set. It raises a KeyError if the set isΒ empty.
4.3) Set Operations
Set provides a useful number of operations to be performed on 2 or more sets. Let us see how we can quickly understand each ofΒ them.
Checking if 2 sets are disjoint:
A disjoint set: The two sets without any common elements.
Checking for aΒ subset:
Use the issubset() method to check whether all elements of a set are contained in anotherΒ set.
Set Union:
Use the union() method to compute the union of two or moreΒ sets.
Set Intersection:
Use the instersection() method to find the common elements of two or moreΒ sets.
Set Difference:
Use the difference() method to compute the difference between two or more sets. It returns a new set containing all items from the first set that are not in the otherΒ set.
Conclusion:
If you are in this line, it means that you have now successfully learned all the basic aspects of βpython collectionβ. I have tried to include as many examples as possible to make reading easy. I will continue to write on the other python programming aspects in the upcoming articles. Happy reading!.
Understanding Python: Part 3 was originally published in Towards AIβββMultidisciplinary Science Journal on Medium, where people are continuing the conversation by highlighting and responding to this story.
Published via Towards AI