Python Lists
In this session, we will discuss about Python Lists – Uses and Features. So far, we have seen the use of variables which can hold only single value. Like var = 1 or str = ”Python”. These variables cannot hold more than 1 value at a time. Either we can change their current value, or we must declare more variables. Now imagine a situation where you are writing a program where you would need 100 or 1000 variables. In such case, using 100 or 1000 variables is not feasible. This provides us with an opportunity to use Lists.
What are Python Lists ?
Lists are variable types that can hold more than 1 value. In short, Lists are multi-value variable. When we have a situation where we want to use too many variables, then lists are a good option.
Example – list = [1,2,3,4]
- In this example, we declared a variable of list type having four values of integer type.
- List always start with an open square bracket and ends with closing square bracket.
- List can have values of any type like integer, float, strings etc.
- All the values/elements of the list must be separated by comma
- We can access list values using indexes. List index always start with 0 which means that first value is stored at index 0, second value is stored at index 1 and so on.
FAQ – Use of Lists in Python
Python lists are multi-value variable that can store more than 1 value. Different values can be of different type like integer, string etc.
Lists are useful when you have requirement to use many variables like 10 or 15 and declaring a different variable for each one of them is not feasible.
Yes, we can put a list inside a list in Python. The list will be treated as a separate element in the main list. We will see how to do that in this session.
We declare a list by using an opening square bracket and ending the list with closing bracket like this – [1]. We can declare an empty list by just writing – []
Using Python Lists:
1. Declaring a Python List of four elements
list = [1,2,3,4]
2. Declaring an empty list having no elements
emp = []
3. Declaring a list with multiple variable types – This is a list having 7 elements which includes integer, float and string
new_list =[1,2,3.8,”Python 3.0”,5,0,9.8]
4. Displaying the list – here we will be using print statement to display the list.
new_list =[1,2,3.8,"Python 3.0",5,0,9.8] print(new_list)
5. Accessing elements using indexing – here we are printing the 3rd element. Now to access third element we have to use index 2 index since index start from 0.
new_list =[1,2,3.8,"Python 3.0",5,0,9.8] print(new_list[2])
6. Assigning list element – here we will change the 6th element of list (index 5) with another value 100
new_list =[1,2,3.8,"Python 3.0",5,0,9.8] print(new_list) print(new_list[5]) new_list[5]=100 print(new_list) print(new_list[5])
7. Assigning value of one list element to another element – here we will assign value of element 3 to element 6
new_list =[1,2,3.8,"Python 3.0",5,0,9.8] print(new_list) print(new_list[5]) new_list[5]=new_list[2] print(new_list) print(new_list[5])
8. Using expression as index – while using index in list, we can also mention some expression in list like below. We have defined another variable n = 1 and while accessing element, we have used a instead of a direct value for index.
new_list =[1,2,3.8,"Python 3.0",5,0,9.8] n=1 print(new_list[n])
Using negative indexes for accessing list elements – Negative index start from -1. This means that index -1 represents the last element of the list, -2 represents the second last element and so on.
9. Accessing list element using negative element
list=[1,"Python","Is","Easy","To","Learn"] print(list[-1]) print(list[-3])
10. Non exiting element of list – while using index for accessing list elements, we have to remember that non existing element should not be accessed else we will get error – IndexError: list index out of range.
Consider below list. Here last element to be accessed using index 9 hence this will give error. Also -11 and -12 will give error because last negative index should be -10
list=[1,2,3,4,5,6,7,8,9,10] print(list[10]) print(list[11]) print(list[-12]) list[12]=150 - IndexError: list assignment index out of range
11. Finding the number of elements in list – using len() function, we can find the number of elements present in the list
list=[1,"Python","Is","Easy","To","Learn"] num=len(list) print("Number of elements in the list is:",num)
12. Using len() to print list elements – here we are using for loop and len() function to iterate over list and print elements
list=[1,"Python","Is","Easy","To","Learn"] for i in range(len(list)): print(list[i],end=" ")
Deleting elements in Python Lists:
13. Deleting list elements – to delete, we have to use del instruction along with the index of the elements. Here also we must make sure that element index is correct, and element is existing.
list=[1,2,3,4,5,6,7,8,9,10] print(list) del(list[2]) - #delete element number 3 print(list)
14. Deleting elements using negative index – here as we discussed -1 means last element and -10 means first element
list=[1,2,3,4,5,6,7,8,9,10] print(list) del(list[-4]) print(list)
15. Delete the whole list – we can delete the complete list itself by just giving the list name
list=[1,2,3,4,5,6,7,8,9,10] print(list) del(list) print(list) – this statement will give error because the list is deleted now
Function vs Method:
Method needs some data, content to work up on | Function itself can created, generate or modify the existing data |
Method is owned by data | Function is not owned by data |
Example – list.append(value) | Example – len(list) |
Adding Elements in Python Lists:
To add elements in the list, we use two methods namely append and insert:
- list.append(value) – this statement will add element value to the end of the list
- list.insert(index,value) – this element will insert element value at index mentioned in parameter. As a result, all the elements currently at the mentioned index as well as to the right of the index will shift one position to the right.
16. Add element at the end of the list – here we will use method append which adds element to the end of list by default. The element value is 6
list=[1,2,3,4,5] print(list) list.append(6) print(list)
17. Add element at some specific index – we will use method insert where we ill provide index and value of the element. Below code will add element 6 at index 3. Hence elements 4(current index 3) and 5(current index 4) will move one position to the right. Hence the index of element 4 and 5 will increment by 1.
list=[1,2,3,4,5] print(list) list.insert(3,6) print(list)
18. Add element “Python” at first location – imagine a list = [“is”,”essy”]
list=[“is”,”easy”] print(list) list.insert(0,”Python”) print(list)
19. Creating list using append method – here we are using for loop and append method to add elements to the empty list
emp_list=[] for i in range(6): emp_list.append(i+1) print(emp_list)
20. Creating list using insert method – here we will use insert method to add elements to the empty list
emp_list=[] for i in range(6): emp_list.insert(i,i+1) print(emp_list)
21. Reading a list using for loop – here we will provide the length of list in for loop range. Range function starts from 0 and end at one value less than the last value. Similarly list index also start from 0 and end at one value less than the list length
list=[1,2,3,4] for i in range(len(list)): print(list[i])
22. Reading a list using for loop – another way to read list in for loop is to directly iterate over list elements instead of specifying the list length in range function
list=[1,2,3,4] for i in list: print(i)
Swapping list elements in Python:
We have already worked on swapping variable values in various other programing languages. The most obvious way was to use a swap temporary variable like below:
23. Swapping variable values – using third temporary variable
x=1 y=2 print(x,y) swap=x x=y y=swap print(x,y)
Here Python provides us a way to swap variables without using the third temporary swap variable like below. See the bold statement. We are directly assigning x=y and y=x.
24. Swapping variable values – without using third variable in Python
x=1 y=2 print(x,y) x,y = y,x print(x,y)
Now using this logic, we can swap the elements of the list.
25. Swap list elements – here we will see how to swap list elements where there are only 4 elements
list=["Python","Java","C","Perl"] print(list) list[0],list[3]=list[3],list[0] list[1],list[2]=list[2],list[1] print(list)
26. Swap list elements – above solution seems good when list length is very small. Imagine we have a list of 6 or 8 elements. Then above solution might now work, and we have to use something like below.
list=["Python","Java","C","Perl","Go","DotNet"] print(list) for i in range(len(list)//2): list[i],list[len(list)-1-i]=list[len(list)-1-i],list[i] print(list)
We are using for loop till half the length of the list. Inside for loop, we are swapping first element with last element, second element with second last element and so on. If we run the for loop till length of the list instead of half of it, then we will get the original list instead of the swapped list. This solution will also work when we have odd number of list elements.
27. Swap list elements – using above solution for odd number of elements in the list
list=["Python","Java","C","Programing","Perl","Go","DotNet"] print(list) for i in range(len(list)//2): list[i],list[len(list)-1-i]=list[len(list)-1-i],list[i] print(list)
List inside list:
We can also achieve nesting of list just like loops. This means that we can put a list as an element inside the list:
28. List inside list- here in the list, we have used another list as 3rd element(index 2) and we can access them in normal indexing way. By using two level index, we can access elements of list present inside list
list = [1,"Python",["2","Java","C"],"Perl"] print(len(list)) print(list[1]) print(list[2]) print(list[2][1]) print(len(list[2]))
29. Try this out – here we are providing variables in the list. But when printing, we will see actual values of the variables. Remember to use only existing variables
a=1 b=2 c=3 list=[a,c,b] print(list)
Previous Session: https://itkaksha.com/difference-between-logical-and-bitwise-operator/
One thought on “Python Lists”