Join thousands of AI enthusiasts and experts at the Learn AI Community.

Publication

Programming

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 Data Structures

“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

  1. List
  2. Tuple
  3. Dictionary
  4. 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.

Figure[1]

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.

Figure[2]

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]

Figure[3]

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.

Figure[4]

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)

Figure[5]

Q 2) Print the last element in the list “a” ?(Use both the accessing techniques)

Figure[6]

Q 3) Print the element “Python” from the list “a” ?(Use both the accessing techniques)

Figure[7]

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.

Figure[8]

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).

Figure[9]

Q 2) Print/Slice all the elements from 4 to True.

Figure[10]

Q 3) Print all the elements of the list without using index values.

Figure[11]

Q 4) Reverse the list elements using a negative indexing technique.

Figure[12]

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].

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.

Figure[14]

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.

Figure[15]

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”.

Figure[16]

Here is a brief description of what each of the built-in list methods does.

Figure[17]

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”.

Figure[18]

clear:

The clear method resets the list to an empty state.

Figure[19]

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).

Figure[20]

count:

It returns the number of occurrences of the specified object in the list.

Figure[21]

index:

It returns the lowest index in the list that the object appears.

Figure[21]

insert:

The object is inserted into the list at the specified index.

Figure[22]

pop:

It removes and returns the last object of the list.

Figure[22]

remove:

It removes the specified object from the list.

Fiigure[23]

reverse:

It reverses the list.

Figure[24]

sort:

It sorts the list in ascending order.

Figure[25]

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.

Figure[26]

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].

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.

Figure[28]

The deletion of an element of a tuple is not possible. However, deleting the entire tuple is possible.

Figure[29]

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.

Figure[30]

index:

It searches the tuple for the first occurrence of a specified element and returns the index value for that particular position.

Figure[31]

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].

Figure[32]
Figure[33]

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.

Figure[34]

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.

Figure[35]

Add an item to the dictionary by using a new index key and assign a value to it.

Figure[36]

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.

Figure[37]

dict.clear():

It is used to delete all the items of the dictionary.

Figure[38]

dict.copy():

It returns a shallow copy of the dictionary.

Figure[39]

dict.fromkeys():

Create a new dictionary from the iterable(list or tuple)with the values equal to value.

Figure[40]

dict.get(key):

It is used to get the value specified for the passed key.

Figure[41]

dict.items():

It returns all the key-value pairs as a tuple.

Figure[42]

dict.keys():

It returns all the keys of the dictionary.

Figure[43]

dict.setdefault():

It is used to set the key to the default value if the key is not specified in the dictionary.

Figure[44]

dict.update():

It updates the dictionary by adding the key-value pair of another dictionary to this dictionary.

Figure[45]

dict.values():

It returns all the values of the dictionary

Figure[46]

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].

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].

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.

Figure[49]

remove:

It removes an element specified by the user.

Figure[50]

pop:

It removes a random element from the set. It raises a KeyError if the set is empty.

Figure[51]

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.

Figure[52]

Checking for a subset:

Use the issubset() method to check whether all elements of a set are contained in another set.

Figure[53]

Set Union:

Use the union() method to compute the union of two or more sets.

Figure[54]

Set Intersection:

Use the instersection() method to find the common elements of two or more sets.

Figure[55]

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.

Figure[56]

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

Feedback ↓