Thanks to visit codestin.com
Credit goes to pyofpython.wordpress.com

Lists- I

After covering loops it’s time to dive into the real python stuffs which I termed as The Fantastic Four: Lists, Tuples, Set and Dictionary. (I am a Marvel Fan after all)

If someone wants to pursue a career in Data Science using python, then, mastering Python’s Fantastic Four features is a must. 

List

Starting with the first feature: List. The first question that comes to mind is what is a list in python? A list in Python is a built-in data structure, used to hold an ordered sequence of values, because python programming doesn’t have the concept of arrays. Lists are similar to arrays in C or Java. Together with tuples, set and dictionary, list dominates the python programming conceptually.

How to write a list?

Let’s write the first list. A list is written in square brackets and the elements inside the brackets are separated by commas.

Here, rainbow is a variable and it contains a list of elements, inside square brackets and separated by commas. Single quotes are used because the elements are non- numeric. We can also check the type of this variable rainbow using the type command.

As you can see, this is a list. The elements in the list can be and cannot be of the same type. For example, the list above has all colors. We can have a list of numbers as well, like, 

There is no need to include single or double quotes when using numeric values. Or, we can also have a list of different types of elements, like

The list above contains both characters as well as numbers. We can also have a list of lists by writing them inside square brackets. Each list will be enclosed in their square bracket as well..

What are the various operations which can be performed on a list?

Indexing

The elements inside a list can be accessed by their index value. The position starts from 0. That is, the first element has the 0th index value; the second element has 1st index value and so on. To access any element, just write the name of the list followed by the index number inside the square bracket. 

The list rainbow has its first element as violet. Let’s check a few more positions.

What about list of lists?

It’s working fine. The second element in list_of_lists is having a list of colors. Don’t get confused by the number [2]. Index starts with [0]. Can we write any index which does not exist for a particular list? Let’s check this rainbow list again.

By simply looking at this list, now, you can say that this list has six index values starting from 0 to 6. 0 means violet and 6 means red. What if someone writes 7?

As expected, an error occurred. This error is known as Index Error. Look at the last line of this error. It shows that, List index is out of range. It simply means that whatever index value has been mentioned, the list doesn’t contain that many elements. Again, the knowledge of these basic errors are handy to troubleshoot. 

One of the most interesting features of list indexing in python is that, the list can be read and accessed from right to left as well. [0] is the first index position when we move from left to right, and, [-1] is the first index position when we move from right to left. If we want to access the last element of our list rainbow, then, we have to write as follows,

Slicing

Slicing is one of the most powerful operations which are used when a portion of a list is required. The remaining part is sliced off. Slicing is performed by using the following syntax-es: 

  1. Listname [index value of first desired element : index value of the last desired element] 

This will give you the list of all the elements which lies in between the two index positions written, including the first element but excluding the last element.

The index position used here is [1:3]. [1] is the index position of Indigo. It will be included. [3] is the index position of Green. It will be excluded. So, anything, starting from Indigo and before Green will be printed. Looking at the rainbow list, Indigo and Blue are the elements left and all others are sliced off.

  1. Listname [index value of first desired element : ] 

This means that all the elements starting from the given index position will be included till the last value. Because the last desired index position is not mentioned, I treat it as infinity. And theoretically, the last value before infinity is the last value of the list.

As you can see, the list starts with index position [2] which is Blue and includes all the remaining elements till the last element which is Red. 

  1. Listname [ : index value of the last desired element]

This will include all elements from starting index position to the second last element of the list, slicing off the last element.

Violet is the first element and Orange is the second last element of the list rainbow having index [5]. Red is sliced off.

Similar to negative indexing, negative slicing is also possible in python.

We now know that [-1] is the last index position of the list. So, rainbow[2 : -1] will include the index position [2] but will take the element which is just before the index value [-1]. It is similar to writing rainbow[2 : 6].

Another important slicing syntax to remember is [: : -1]. This special operation will give a reversed copy of your list. Two colons followed by -1, all inside square parenthesis. This comes out to be very useful in solving many problems.

The entire list is reversed. 

List Mutability

Lists are mutable. By this, it means that lists can be modified. The values can be changed and reassigned depending on the requirement. Let us see how to change a list. Taking the list of numbers,

Let’s add some new numbers to it and then remove some. Reassigning the whole list first,

Now adding two new numbers 11 and 12 in place of 3. We will use a slicing method. The index value of 3 is [2]. Let’s see what happens next?

This reassigned the number 11 and 12 in place of 3 which is the [2] index position or the 3rd element. [2 : 3] means that the 2nd index position or 3rd element is replaced with the given value. Here, we had two values to be substituted in this place, 11 and 12. Let’s bring back 3 as well.

So, it means that [2 : 2] is equivalent to “replace 2nd index value or 2nd element with the given value”, which is 3 here. Let’s add another number to this list at the last position. There are 11 index positions in this list. [12] is needed to add a number at the last position.

An error!!! Why did this happen? If we analyse this error, it’s Index Error. So, once a list is created it’s length or range is determined by python. And then, element cannot be added to the last position. Can we add 13 to any other position?

It’s working. Let’s delete the numbers now and bring back our original numbers list. Del command is used to perform deletion operations. Index can be used to delete a single element.

For deleting a batch of numbers, slicing can be used along with del command.

It can be seen that 3rd and 4th index value numbers have been deleted.

String Concatenation

It is used to join two lists and the order is also maintained. A “+” sign is used to concatenate two lists together.

List Functions

There are numerous built-in functions that can be used on python list. Some of the common functions are:

len (): It gives the length of the list, i.e., how many elements are present in the list.

max (): It gives the maximum value of element from the list. The list must be numeric type. 

For string type elements, it compares and gives the maximum value.

But it fails when the elements are string as well as integers. Let’s see the error. It’s Type Error. Data types are different and hence comparison is not possible.

min (): It gives the minimum value of element from the list.

sum (): It gives the addition of all values of elements from the list. Again, it’s valid for integers or numeric data type of elements only. 

sorted (): It will sort the element of the list in increasing order.

For string data type the sorting is done according to their ASCII value. 

list (): It will convert any iterable non-integer data type into a list.

What does the word iterable mean here? See the following examples and you’ll easily understand.

any (): It gives the output as True if even one item in the python list has a True value. If the list is empty, it returns False.

all (): It gives the output as True if all the items in the python list has a True value. If the list is empty, it returns true.

List Methods

A function is something that you can apply on a construct and get a result, while a method is what you can do to it and change it. Following are the built-in python list methods:

append (): It is used to add any item in a list at the last position.

extend (): It is used to add the elements of a list as a single argument to another list. It extends the length of the list by one.

insert (): It is used to insert any item in an already existing list at any desired position..

The first value is index position and second value is the item to be inserted. (3, 6) means that at index position [3] value 6 is inserted in the numbers list.

remove (): It is used to remove any element present in the list. Similar to index(), it also checks for the first instance.

If any element is occurring more than once, then, only the first instance is removed. In the code below, 6 is occurring two times. remove() will remove the first 6 only.

pop (): It removes the element at the specified index, and displays it on the screen. 

When the index position is not mentioned, it is used to remove and return the last element present in the list.

clear (): It is used to clear the list or empty the list.

index (): It gives the first matching index of any element from the list. If there is a repetition of any element, then, only the first occurrence is taken into account. It is used to search any element present in the list and at what position.

count (): It gives the count of any element present in the list.

You can see that count () takes exactly one argument. It means that you cannot count more than one element at a time.

sort() and sorted (): It arranges the elements of the list in ascending order by default. If we want to sort the list in descending order, then we have to pass a parameter reverse = True. It simply means that we want to reverse the default condition of sorting.

reverse (): It reverses the order of elements of the list.

Let’s search for orange in the rainbow list. 

It’s true. Orange color is present at 5th position. What about black color?

Oops!!! Black is not present. It’s a small list of 7 colors and is visible what is present and what is not. But think of a list having 70 or 700 elements and you have to check whether a particular item belongs to that list or not. Searching the list can also be done by using “in” operator. It gives an output in Boolean form.

There is an important function called enumerate. With the help of this function, we can print the list elements with their index position. First let’s do the same thing without enumerate function.

I have a list which consists of Heros name. To get the index I need the length of the function. My loop will iterate till the length of the list. For example, if there are 4 elements, then the length will become 4 and the output will be 0, 1, 2, 3. Let’s see how to write it.

The list name followed by square bracket with x as parameter will give the index value.

Another way is to use the enumerate function. It takes two values. The first value will print the list elements and the second value will print the index. Here, x and y are these two values.

By default the index starts with zero. If you want to start with some other number, you can write it inside enumerate function as follows.

Here, I write 2. So the index is starting from 2. Note that it’s like the serial number. It’s not starting with the element starting from the 2nd index position.

Before wrapping up these basic list methods and functions, one last conceptual list method is to be discussed: How to copy elements of one list to another list? Say, I have a list a and I want to copy it’s elements in a new list say, list b.

As you can see in the above code that by simply assigning list to another variable performs the copying operation. Now in the 4th line you can see that we have appended a new value to the new list only. But when we print the original list it has been modified also with the same value as the newly created list.

We can see that original list is modified, as well as new list is updated. This copying method is called Shallow Copy. What if we want that any change in the updated list should not modify the original list? This method of copying is called Deep Copying.

Let’s say I have a list my_list. And I want to copy it’s element into another list, say, new_list. For this copy() method is used.

You can observe the first & second lines to copy the list elements. There is no need to pass any parameter within the copy() method. Now, in the 3rd line I am appending a new value 8 in the new_list and then we are printing the original and the new list. The deep copy can also be performed using slicing operator as shown below.

Another method to perform deep copy is to use a function called deepcopy. For this, we first have to import a module called copy. Module is like a special library or container. Later on, in some article we’ll learn about python modules. For the time being let’s understand that modules are special libraries holding special functions. To use those special functions we need to import them via their modules.

So, our copy module holds the special function deepcopy which is used to perform deep copy operation. You can see the first three lines of the above code. In the 5th line we append some element in our new list and then printed out both the lists. The output clearly suggests that only list b is updated and the original list is left unmodified.

That was all about list methods and functions. You can also watch these list methods on YouTube and the copy methods also on YouTube by clicking here.

Design a site like this with WordPress.com
Get started