Python Programming – Python Lists
In Python, the most basic data structure is the list. The list is similar to the array as in C, C++, or Java since the index of the first element of the list is zero, the second element is one, and so on. However, the list is a collection of heterogeneous data elements. That means a list can contain numeric as well as character data.
Various sorts of operations can be performed on lists. These include indexing, slicing, adding, multiplying, and checking for membership. We will present all these operations through illustrations in the following sections. Apart from that, the Python language also contains various built-in functions, we will discuss them as well.
- Python Programming – List Manipulation
- Python Programming – Standard Data Types
- Python Programming – Introduction To Numpy
Creating a List
It is very simple to create lists in Python. All you need to do is to place all the comma-separated elements inside a square bracket [ ]. The list can contain any number of elements of different data types (integer, float, character, etc). Moreover, a list can contain another list and it is referred to as a nested list. The Code 5.6. illustrates the creation of a list. In this program, we see that three lists are created. The first list name is the new list, which is a simple list with homogeneous data elements. The second list new_listl represents a collection of heterogeneous data elements, and the third list new_list2 represents a nested list. The output can be verified in the output section.
Code: 5.6. Illustration of creating a list.
#Illustration of creating a list
new_list=[1-, 2, 3, 4] # Homogeneous data elements new_listl=[1, “John”, 55.5] # Heterogeneous data elements newHist2=[1 1 1 , [1, “Clara”, 75.5]] # Nested list |
Output [1,2, 3, 4] [1, ‘John’, 55.5] [1 1 1,[1, ‘Clara’, 75.5]] |
Traversing a List
Traversing refers to accessing or visiting elements of a list. The Python language provides different ways in which we can access the elements of a list. These are indexing, negative indexing, and slicing. We discuss each of them with programming illustrations.
Indexing
As in other languages, such as C, C++, & Java, the index of elements of a list starts from 0. Therefore, if a list contains 10 elements then its index will vary from 0 to 9. If a user tries to access an element from a list beyond the range will result in an IndexError. Apart from that, the index of a list is always an integer number. If a user tries to access a list element using floating-point indexing, will result in TypeError.
In order to access the list elements, the indexing operator also called subscript operator [ ] is used. The programming illustration of accessing elements of a list is given in Code 5.7. In the program, a data list with five elements is created. Then, the elements 0, 2, and 4 of the list are displayed by using the index operator [ ].
Code: 5.7. Illustration of list traversal.
#Illustration of traversing a list
datalist=[23, 45, 31, 53, 62] |
Output
23 |
Another programming example of traversing is given in Code 5.8, in which we see that while accessing a list element beyond its range results in an error. In this program, we see that the element at index 5 is accessed. Since the data list contains 5 elements with index 0 to 4. Therefore, accessing the value at index 5 results in an IndexError as shown in the output.
Code: 5.8. IndexError illustration.
#Illustration of traversing a list beyond range
datalist=[23, 45, 31, 53, 62] |
Traversing Nested Lists
By using the index operator the nested list can also be traversed very easily. The illustration for the same is given in Code 5.9. In this program, we see that two nested lists are created as members of the data list. The first nested list is at location index 1 and the other is at location index 2. Therefore, the name elements John and Sandra of these nested lists are accessed as datalist[l][l], and datalist[2] [ 1 ].
Code: 5.9. Illustration of traversal of a nested list.
#Illustration of traversing a nested list
datalist=[l, [1001, ’’John1′, 45.5], [1002, “Sandra”, 56.5]] print(datalist[l][l]) |
Output
John |
Negative Indexing
The Python language also allows negative indexing. However, these features are not available in other languages C, C++, and Java. The index of -1 refers to the last elements of the list, the index -2 refers to the second last element, and so forth. The illustration for the same is given in Code 5.10. However, if the indexing goes beyond range then IndexError occurs as the list index out of range.
Code: 5.10. Illustration of negative indexing.
#Illustration of traversing a list using negative indexing
datalist=[23, 45, 31, 53, 62] |
Output
23 |
Slicing
The slicing operator is used to access the list elements within a specific range. The symbol of the slicing operator is the colon (:). The programming representation for understanding the concept is given in Code: 5.11. In this program, we create a data list with five elements. The slicing operator is used with different ranges of positive as well as negative indexing. The first range is set to be 0:3 that means the elements with index value 0 through 2 will be displayed. It is to be noted that in the syntax of the slicing operator [beg: end], the end is excluded from the range. Thus, the datalist[0:3] results into [23, 45, 31]. Similarly, for the other examples. The just [:] displays all the elements of a list from beginning to end.
Code: 5.11, Illustration of slicing operator.
#Illustration of slicing operator
datalist=[23, 45, 31, 53, 62] |
Output [23,45, 31] [31, 53] [23] [45, 31, 53, 62] [23, 45, 31, 53, 62] |
Changing or Adding Elements to a List
As we know that lists are mutable. That means the elements of a list can be changed or new elements can be added to a list. The process can be performed with the help of the assignment operator (=). The programming example representing the updating elements in a list is given in Code 5.12. In this program, we see that the value of the third element of the data list is changed to 60 and the value of the fifth element is changed to 12. This is performed very easily by using the assignment operator (=).
Code: 5.12. Illustration of changing elements of a list.
#illustration of changing elements to a list datal,ist=[23, 45, 31, 53, 62] datalist[2]=60 datalist[4]=12 print(datalist[:]) |
Output
[23, 45, 60, 53, 12] |
An element can be added to a list by using the built-in Python method append() and if the user wants to add more than one element to a list then this can be performed with the help of the Python built-in extend () method. The programming code for the same is given in Code: 5.13. In this program, we see that a new element 39 is added to the list by using the append () method. For adding more elements to a list extend () method is used, which adds three more elements to the data list. Finally, the newly updated list is displayed as shown in the output.
Code: 5.13. Illustration of adding elements to a list.
#Illustration of adding elements to a list
datalist=[23, 45, 31, 53, 62] |
Output
[23, 45, 31, 53, 62, 39, 76, 23, 15] |
List Methods
In the previous section, we discussed append ( ) and extend ( ) built-in methods of Python. Apart from that, the Python language provides various built-in methods to make the use of lists easier as compared to that of arrays in C, C++, or Java. The Table 5.5. presents various Python built-in methods to be applicable on lists with the description of each.
Method | Description |
append(p) | Adds element p at the end of the list |
extend(L) | Adds list L to the end of the existing list |
insert(i, p) | Inserts, element p at location i of the list |
remove(p) | Removes the first element, which is equal to p from the list |
index(p) | Returns the index of the first element that is equal to p |
count(p) | Returns the occurrence (number of times) of element p in the list |
PoP([i]) | Removes and returns item at location i in the list, (returns last item if i is not provided) |
copy( ) | Returns a copy of the list |
clear( ) | Removes all elements from the list and returns the empty list |
sort( ) | Sorts the elements in the list |
Reverse( ) | Reverses the order of elements in the list |
All the methods provided in Table 5.5. are beneficial for implement data structures such as stack, queues, lists, etc. The programming example representing the use of the above methods is given in Code 5,14. From the output of the program, the operation of each method can be understood very easily.
Note:
All the list methods are accessed using dot (.) operator with the list name.
Code: 5.14. Illustration of list methods.
#Illustration of list methods
datalist=[23, 45, 31, 53, 62] |
Output
[23, 45, 31, 53, 62, 39, 76, 23, 15] |
List Functions
Function | Description |
cmp(listl, list2) | Compares elements of both lists |
len(list) | Gives the total length of the list |
max(list) | Returns the largest element from the list |
min(list) | Returns the smallest element from the list |
list(seq) | Converts a tuple into list. |
In addition to list methods as described in the previous section, the Python language also provides various list functions. The list of built-in Python list functions is given in Table 5.6. The programming illustration of len, max, and min is presented in Code 5.15. It is apparent from the output that the length of the given list is 5, the largest elements is 62 and the smallest element is 23.
Code: 5.15. Illustration of list functions.
#Illustration of list functions
datalist=[23, 45, 31, 53, 62] |
Output
5 |
List Comprehension
The Python language provides a very useful feature known as a list comprehension. It provides an extremely efficient and concise way to create a new list from an existing one. In list comprehension, a for a statement or an optional if statement is used to create a list from the wide range of lists. All the process is performed inside square brackets representing a list. The programming illustration to extract even and odd numbers out of a list of 1 to 50 numbers is given in Code 5.16. In the programming code, we see that an event list is created out of a list of 1 to 50, numbers based on the if condition i%2==0. Similarly, an odd list is created out of a list of 1 to 50 numbers based on the if condition i%2!=0. We can see from this feature that the Python language provides efficient and concise codes for solving large problems. For instance in the programming Code 5.16., only one line of code is used to obtain even numbers from 1 to 50, which can be extended up to 1 to n numbers. The same is true for the odd number list.
Code: 5.16. Illustration of list comprehension.
#Illustration of list comprehension.
even=[i for i in range(50) if i%2 == 0] |
Output [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48][1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49] |
List Membership Test
The most important data structure operation is the searching. In Python, an element from a list can be searched very easily. The ‘in’ operator is used to determine whether an element exists in the list. It returns true if elements exist otherwise false. The programming illustration for the same is given in Code 5.17. The code is quite simple. We search for element 11 first, as it is present in the list so the output comes out to be true. Another test is performed for element 66, as it does not exist in the list and thus the result is false.
Code:5.17. Illustration of list membership test.
#Illustration of list membership test
datalist=[l 1, 22, 33, 44, 55] |
Output
True |
The ‘in’ operator is also used to iterate through the list using for loop. The programming example is presented in Code 5.18. It is apparent from the code that using for loop all the elements of the list can be accessed and processed efficiently.
Code: 5.18. Illustration of iterating through the list.
#Illustration of iterating through the list
for city in [‘Goa’, ‘Mumbai’, ‘Chennai’]: |
Output I visited Goa I visited Mumbai I visited Chennai |
Recommended Reading On: Java Program to Remove Odd Numbers from Array