Understanding the Data structures is the most crucial and important thing when it comes to learning and working with any programming language. Python too has some of the most popular data structures using which you can organize the data in memory. List, Tuples, Sets, and Dictionary are some of the widely used data structures in python. We will discuss the List in python data structure in detail in this blog post. Later we will see some of the other data structures in python in detail.
For more blogs visit LionGuest Studios.com
- The List is a data structure in python which stores data linearly or sequentially one after the other. It is somewhat similar to arrays in other programming languages. The only difference between an array and a List is the arrays can store data of the same type whereas Python’s List can store data with multiple data types (a combination of integer, string, floating-point, etc).
- Lists are represented using square brackets [ ]. The initial item in a list starts with an index number ‘0’.
- The list is a mutable data structure which simply means that once it has created the items inside which can be changed later.
Lists can be created by putting values inside the square brackets and assigning it to a variable.
empty_list = [ ]
Here, empty_list is the name of the variable which will contain a list as represented by square brackets. And inside the square brackets, you don’t have any elements which simply means that the list is empty.
list_of_numbers = [ 1, 2, 3, 4, 5] list_of_Strings = ['Ana', 'Pat', 'Simon', 'Amanda']
Note that the strings inside the list are represented by quotes (single or double quotes anything will work) and numbers have no quotation mark.
list_with_different_data_types = [ 'Micheal', 15, 20.5, [1, 2, 3] ]
This is a list that contains multiple data types. Also, the lists can contain another list too. In this case, element number 3 is an element of a list which is a list in itself.
There are two ways in which you can add an element into a list. The extend() function will be discussed later in this blog post.
1. append() function:
If you want to insert an element at the end of the list then you can use the append function. Inside this function, you have to pass the value or the element that needs to be inserted in a list.
original_lst = ['A', 'B', 'C', 'D', 'E'] original_lst.append('F') #This will insert element ‘F’ at the end of the list print(original_lst)
Output: ['A', 'B', 'C', 'D', 'E', 'F']
You can even insert an entire list to an already created list with the append() function.
lst = ['A', 'B', 'C', 'D', 'E'] new_lst = ['F', 'G', '1', '2', '3'] lst.append(new_lst) print(lst)
Output: ['A', 'B', 'C', 'D', 'E', ['F', 'G', '1', '2', '3']]
Note: If you want to add a single element to a list then use append() and if you want to add multiple elements into a list then use extend(). Go to extend() function.
2. insert() function:
If you want to insert an element at a specified location in a list then you can use the insert(location, element_to_insert) function which takes two parameters. In the first parameter, you have to pass the location at which the element is to be inserted and in the second parameter, you have to pass the value of the element.
my_list = ['one', 'three']
Now let’s add element ‘two’ to the above list at index 1 for that you have to use the insert function.
my_list( 1, 'two' )
After inserting the element ‘two’ at index 1, the element which is currently present at that location will be moved to the next index (in this case at index 2).
Output: ['one', 'two', 'three']
1. remove() function:
If you want to delete a particular element from a list using its value then you can use the remove() function. For example, if you want to remove element ‘B’ from the list then you have to pass this as an argument to the remove() function.
list = ['A', 'B', 'C', 'D', 'E'] list.remove('B') print(list)
Output: ['A', 'C', 'D', 'E']
2. del keyword:
If you want to delete a particular element from a list using its index then you can use the del keyword. Let say you want to delete ‘Marry’ from the below list then you can delete that element using its index no.
list = ['Merry', 'Adam', 'Watson', 'Anna'] del list #passing index 0 because Marry is present at the index print(list)
Output: ['Adam', 'Watson', 'Anna']
3. pop() function:
The pop() function works the same way as the del keyword but the only difference is that the pop() function will also return the element which has been deleted from the list.
list = ['Merry', 'Adam', 'Watson', 'Anna']
item_popped = list.pop(0)
Output: Marry ['Adam', 'Watson', 'Anna']
So, If you want to delete an element from a list in python using the value then use the remove() function. And if you want to delete an element using index no then use the del keyword or pop() function. In case if you also want to get the item that you have deleted then use the pop() function which will return you that item.
Each element in a list as an index no starting with zero. To find an element inside the list you have to use its index no. Accessing an element using its index no is called indexing. This can be done by passing the index number inside the square brackets.
In the below list, if you want to access the individual elements inside a list then you can pass the index as follows.
my_list = ['one', 'two','three'] print(my_list) # accessing element ‘one’ print(my_list) # accessing element ‘two’ print(my_list) # accessing element ‘three’
Output: one two three
Slicing is nothing but dividing a list. In case if you want to print some part of the list and not the entire list then you can use slicing.
Slicing is done using “:” colon symbol. It has 3 parts list[ start : end : stepSize ]. Step size is optional.
Before the colon, you have to specify the start index of the list (i.e the index from which you want to slice a list) and it is denoted by start. After the colon, you have to specify the end index of the list (till what index do you want to slice the list) and it is denoted by the end. Here, note that the value which you specify for the end part will not be included in the final list after slicing.
Let’s take an example and understand this.
slice_this_list = [10, 20, 30, 40, 50, 60]
Here, we have a list of 6 elements. Now let’s say you want to slice or divide a list from the 2nd element i.e 20 till the 5th element i.e 50 to get the final result as 20, 30, 40, 50 as our output.
So, to slice them you have to use the index number of both the start and the end elements. The index of starting element 20 is 1 and the index of ending element 50 is 4. You will use these index nos in order to slice the list.
print(slice_this_list[1 : 4])
What do you think it will print? It will print 20, 30, 40 only 3 elements. But we also want to print 50, right? The last element is not included in the slicing because python will exclude the end and will stop at one index before the end i.e in this case index 3.
You have specified end as 4, so it will stop at one element before index 4 which is index 3. And the element which we have at index 3 is 40. Therefore, it is slicing till element 40.
Now, if you also want to get the element 50 then you have to increase our end index to 5.
print(slice_this_list [ 1 : 5 ])
Here, you are slicing the list in sequential order (one after the other) but if you want to skip some elements in the middle then you can use step size. By default step size is 1 which will slice the elements in sequential order. You can increase it to any value, in this case, let’s increase it to 2.
print(slice_this_list [ 1 : 5 : 2 ]) # Here, # 1 represents - start # 5 represents - end # 2 - represents - step size
This will print the following as output.
Output: 20 40
In case if you want to start from a particular element and then print all the elements then don’t specify the end part keep it blank.
my_list = [10, 20, 30, 40, 50, 60, 70]
Here, Let’s start printing from the element 30 to the last element i.e 70.
print(my_list[ 2 : ]) #end part is kept blank to print rest of the elements in the list
Output: [30, 40, 50, 60, 70]
The same can be done if you want to print all the elements from the staring index to the desired element. Let’s slice the above myList till the index 5. For that keep the start part blank.
print(my_list[ : 5 ]) #end part is kept blank to print all the in the list after
Output: [10, 20, 30, 40, 50]
Note that it will slice till one element before the index 4.
Sorting a list is arranging the elements inside the list in either ascending or descending order. There are two ways to sort a list in python.
1. sorted() function:
sorted() function takes a list as an input and returns a sorted list in ascending order. The original list remains unchanged. Now if you want to sort the list in descending order then you can even pass reverse = True as a second argument (which is optional) to the sorted() function.
original_list = [5, 2 , 1, 4, 3] sorted_list_ascending_order = sorted(original_list) sorted_list_descending_order = sorted(original_list, reverse= True) print(original_list) print(sorted_list_ascending_order) print(sorted_list_descending_order)
Output: [5, 2 , 1, 4, 3] [1, 2, 3, 4, 5] [5, 4, 3, 2, 1]
2. sort() function:
Instead of creating a new variable and storing the sorted list inside that variable, you can also sort the list and store it inside the same variable using the sort() function.
original_list = [5, 2 , 1, 4, 3] original_list.sort() print(original_list)
Output: [1, 2, 3, 4, 5]
Note that if you have a list with different data types then you cannot sort that list with any of the above functions as it is not possible.
In order to print all the elements inside a list in python you can use a for loop with the “in” keyword.
list = [1, 2, 3, 4, 5] for element in list: print(element)
Output: 1 2 3 4 5
1. Reversing a List in python
list.reverse(): Reversing a list in python is very easy. In order to reverse a list, you have to use the reverse() function in python which will reverse all the elements inside that list.
reverse_this_list = [5, 10, 15, 20, 25, 30] print(reverse_this_list.reverse());
Output: [30, 25, 20, 15, 10, 5]
2. Finding length of a list
len(List): If you want to know the total no of elements inside a list then you can use a len() function which will return the total elements present inside the list.
find_length_of_list = [10, 20, 30, 40, 50] print(len(find_length_of_list))
3. Splitting a string into a list in python
string.split(): If you have a string say “Welcome to LionGuest Studios” and want to split the entire string in such a way that each word in a string is represented as an element inside a list. For that, you have to use the split() function. If you don’t specify any parameter then it will split the string based on white space or a tab.
string_to_list = "Welcome to LionGuest Studios" string_to_list.split()
Output: ['Welcome', 'to', 'LionGuest', 'Studios']
4. Joining two or more List in python
a. extend() function:
If you want to add elements at the end of the list or if you want to join two lists then you can use the extend function. This will add elements of list2 to list1 without affecting list2.
#example with "extend" list1 = [1, "Mac", 20.5] list2 = ["Mongo", 50, 40.5] list1.extend(list2) print(list1) print(list2)
Output: [1, 'Mac', 20.5, 'Mongo', 50, 40.5] ['Mongo', 50, 40.5]
Note: If you want to add a single element to a list then use append() and if you want to add multiple elements into a list then use extend().
b. “+” operator
To join two or more lists together we can use the “+” operator. This works the same way as the extend function but here it will not modify the given lists. You have to store the results of this operation to a new variable so that you can use it later.
#example with "+" list1 = [1, "Mac", 20.5] list2 = ["Mongo", 50, 40.5] list3 = ['X', 'Y', 'Z'] new_list = list1 + list2 + list3 print(list1) print(list2) print(list3) print(new_list)
Output: [1, 'Mac', 20.5] ['Mongo', 50, 40.5] ['X', 'Y', 'Z'] [1, 'Mac', 20.5, 'Mongo', 50, 40.5, 'X', 'Y', 'Z']
5. Counting occurrence of an item in a list
list.count(): In order to count the total occurrence (frequency) of a particular element in a list we can use the count function.
this_list = [10, 20, 30, 20, 10, 50 ,20 ,20] # To count the occurrence of number 20 count_of_no = this_list.count(20) print("Total number of times the no. 20 has occured in a list is:", count_of_no)
Output: Total number of times the no. 20 has occured in a list is: 4
That’s all it is. Thanks for the read. If you like the content then support us on Patreon. Your support will surely help us in writing more of such content.
To read more such blogs about Python programming related stuff visit our blogs page on LionGuest Studios.