In this tutorial, we will learn about List in Python and we will also cover different examples related to Python List. And, we will cover these topics.
- Python List
- Characteristics of Lists
- List indexing and splitting
- Updating list values
- Python List Operations
- Iterating a List
- Adding elements to the list
- Removing elements from the list
- Python List Built-in functions
Python List
In Python, a Python list is used to store the various types of data and store the multiple types of data in a single variable. In the Python list, it can modify its element after it is created. There are six data types in python out of which the list is very reliable.
A list can be defined as the collection of objects, values, or items. We separate the items in the list using the comma (,) and enclosed them using the square brackets ([]).
With the following example, we can better understand how we can define the list.
L1 = ["Pythontpoint",2021, "INDIA"]
L2 = [1, 2, 3, 4, 5, 6]
If we check to print the L1 and L2 types using the type() function it is visible to us in the following way.
Output:
Characteristics of Lists
- Lists are Dynamic
- The list can be modified
- The Lists are ordered
- The list can store various elements and data.
- The elements in the list can be accessed by the index.
Here is the following example of a python list:
emp = ["Peter Parker", 98102, "LA,USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Bravo Holding"]
HOD_IT = [11, "Mr. James Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:
After running the following code we get the following output in which we have created a list that consists of employees and department information and printed corresponding to the screen.
With the help of the above code, we can better understand the concepts of the list while understanding or reading the code.
List indexing and splitting
The list Indexing is the same process as it happens in the strings. We can access the elements of the list using the slice operator ([]). The starting of the index is 0 and goes to length -1.
In index, the first element is stored at the 0th Index and the second element is stored at the 1st index and so on it moves in this sequence only.
List=[0,1,2,3,4,5]
To find the sublist we need to follow the following syntax:
list_varible(start:stop:step)
- The start indicates the starting index position of the list.
- The stop indicates the last index position of the list.
- The step is used to skip the nth element within a start:stop
We can better understand indexing and slicing using the following example:
Code:
In the below Code we have followed the following steps:
- print(lst[0:6]) is used for slicing the elements
- Note: By default, the index value is 0 so it starts from the 0th element and goes for index -1.
lst = [1,2,3,4,5,6,7]
print(lst[0])
print(lst[1])
print(lst[2])
print(lst[3])
print(lst[0:6])
print(lst[:])
print(lst[2:5])
print(lst[1:6:2])
Output:
The python also provides negative indexing also. It is counted from the right side and the last element of the list index is -1.
Here using the following example we can better understand the negative indexing and how we can access the list:
Code:
lst = [1,2,3,4,5]
print(lst[-1])
print(lst[-3:])
print(lst[:-1])
print(lst[-3:-1])
Output:
In the early, as we discussed that we can also get the elements of the list using negative indexing.
After running the above code the first print statement is returning us the rightmost element of the list and the second print statement is returning the sub-list and so on.
Read: Python String
Updating list values
In python, lists are the most flexible data structure since they can be changeable or modified and we can update their values using the slice and the assignment operator.
Python also provides us with the append() and insert() method to add the values to the list.
By using the following example we can better understand how we can update the value inside the list:
Code:
In the below Code we have followed the following steps:
- lst[2] = 10 is used because it will assign value to the value to the second index.
- lst[1:3] = [23, 8] is used to add multiple-element.
- lst[-1] = 25 is used because it will add value at the end of the list.
lst = [1, 2, 3, 4, 5, 6]
print(lst)
lst[2] = 10
print(lst)
lst[1:3] = [23, 8]
print(lst)
lst[-1] = 25
print(lst)
Output:
In python list, we can also delete the list element using the del keyword even it also provides the remove() method which is used when we don’t know which element is deleted from the list.
Python List Operations
In Python list the concatenation (+) and repetition (*) operators work the same as the way they were working with the strings.
With help of the below table let’s understand how the list responds to various operators.
Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.
Operator | Description | Example |
---|---|---|
Repetition | The repetition operator enables the list elements to be repeated multiple times. | L1*2 = [1, 2, 3, 4, 1, 2, 3, 4] |
Concatenation | It concatenates the list mentioned on either side of the operator. | l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8] |
Membership | It returns true if a particular item exists in a particular list otherwise false. | print(2 in l1) prints True. |
Iteration | The for loop is used to iterate over the list elements. | for i in l1: print(i) Output1 2 3 4 |
Length | It is used to get the length of the list | len(l1) = 4 |
Iterating a List
The list is the type of container in a data structure that stores multiple values at the same time In python lists are ordered and have a definite count.
The list can be Iterated in many ways we can understand this by looking below at the example:
Code:
In the below code the x variable will iterate over the elements of the list and contain each element in each iteration.
lst = ["Jonny", "Dravid", "Williom James", "P.Jonathan"]
for x in lst:
print(x)
Output:
Adding elements to the list
In python, to add the elements in the list we use the append function with the help of the append function we can add the elements to the list but it only add the elements at the end of the list.
We can consider the following example to better understand how we can add the elements to the list.
Code:
In the below Code we have followed the following steps:
- Declaring the empty list
- The number of elements will be entered by the user
- for loop to take the input
- The input is taken from the user and added to the list as the item
- traversal loop to print the list items
list =[]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
list.append(input("Enter the item:"))
print("printing the list items..")
for i in list:
print(i, end = " ")
Output:
Removing elements from the list
In python, it also provides us the remove() function which is used to remove the elements from the list. We can consider the following example of how we can remove the elements from the list.
Code:
l = [5,8,9,10,15,20]
print("printing original list: ");
for i in l:
print(i,end=" ")
l.remove(15)
print("\nprinting the list after the removal of first element...")
for i in l:
print(i,end=" ")
Python List Built-in functions
In python it follows some built in function which we can understand that using the following table.
SN | Function | Description | Example |
---|---|---|---|
1 | cmp(list1, list2) | It compares the elements of both the lists. | This method is not used in the Python 3 and the above versions. |
2 | len(list) | It is used to calculate the length of the list. | L1 = [1,2,3,4,5,6,7,8,9] print(len(L1)) Output: 9 |
3 | max(list) | It returns the maximum element of the list. | L1 = [12,34,26,98,72] print(max(L1)) Output: 98 |
4 | min(list) | It returns the minimum element of the list. | L1 = [10,34,26,48,72] print(min(L1)) Output:10 |
5 | list(seq) | It converts any sequence to the list. | str = “John” s = list(str) print(type(s)) Output: <class list> |
Extras:
Write a program to find the sum of the element in the list.
Code:
l1 = [23,10,25,39,40,112,324]
s = 0
for i in l1:
s= s+i
print("The sum is:",s)
Output:
Let us Learn with Errors
code:
When we perform this task we make a small mistake that generates an error and that does not give the correct output.
l = [5,8,9,10,15,20
print("printing original list: ");
for i in l:
print(i,end=" ")
l.remove(15)
print("\nprinting the list after the removal of first element...")
for i in l:
print(i,end=" ")
Error Output:
We can see the output having the syntax error.
- To solve this error we understand the code and read that code again as we found we have not added the Square brackets.
- After adding the square bracket our error was removed.
So, in this tutorial, we discussed Python List and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.
- Python List
- Characteristics of Lists
- List indexing and splitting
- Updating list values
- Python List Operations
- Iterating a List
- Adding elements to the list
- Removing elements from the list
- Python List Built-in functions
You could definitely see your enthusiasm within the paintings you write. The world hopes for even more passionate writers such as you who are not afraid to mention how they believe. At all times follow your heart.
I was studying some of your articles on this site and I believe this internet site is very informative! Keep on posting.