Python List
Python List
There are four collection data types in the Python programming language:
Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and
reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].
L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
The list has the following characteristics:
Let's check the first statement that lists are the ordered.
a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b
Output:
False
Both lists have consisted of the same elements, but the second list changed the index position of the 5th
element that violates the order of lists. When compare both lists it returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of objects.
a == b
Output:
True
Dep1 = ["CS",10]
Dep2 = ["IT",11]
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:
printing departments...
Department 1:
Department 2:
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
In the above example, we have created the lists which consist of the employee and department details
and printed the corresponding details. Observe the above code to understand the concept of the list
better.
The index starts from 0 and goes to length - 1. The first element of the list is stored at the
0th index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative
indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent
left element is present at the index -2 and so on until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to access the elements of
the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As we discussed above, we can get an element by using negative indexing. In the above code, the first
print statement returned the rightmost element of the list. The second print statement returned the
sub-list, and so on.
Python also provides append() and insert() methods, which can be used to add values to
the list.
Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
# Adding multiple-element
print(list)
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
The list elements can also be deleted by using the del keyword. Python also provides us the remove()
method if we do not know which element is to be deleted from the list.
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.
Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.
Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can
be iterated as follows.
for i in list:
# The i variable will iterate over the elements of the List and contains each element in each iteration.
print(i)
Output:
John
David
James
Jonathan
Python provides append() function which is used to add an element to the list. However, the append()
function can only add value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user and
printing the list on the console.
l =[]
for i in range(0,n):
# The input is taken from the user and added to the list as the item
for i in l:
Output:
25 46 12 75 42
Example -
list = [0,1,2,3,4]
for i in list:
print(i,end=" ")
list.remove(2)
for i in list:
print(i,end=" ")
Output:
01234
0134
Python List Built-in functions
Python provides the following built-in functions, which can be used with the lists.
1 cmp(list1, list2) It compares the elements of This method is not used in the Python 3 and
both the lists.
the above versions.
Example: 1- Write the program to remove the duplicate element of the list.
list1 = [1,2,2,3,55,98,65,65,13,29]
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Output:
Example:2- Write a program to find the sum of the element in the list.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
Example: 3- Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
Example
Create a List:
print(thislist)
Output
print(thislist[1])
Output
Banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last
item etc.
Example
print(thislist[-1])
Output
Cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
print(thislist[2:5])
Output
Note: The search will start at index 2 (included) and end at index 5 (not included).
print(thislist[:4])
Output
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
print(thislist[2:])
Output
Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
print(thislist[-4:-1])
Output
thislist[1] = "blackcurrant"
print(thislist)
Output
You can loop through the list items by using a for loop:
Example
for x in thislist:
print(x)
Output
apple
banana
cherry
if "apple" in thislist:
To determine how many items a list has, use the len() function:
Example
print(len(thislist))
Output
Add Items
To add an item to the end of the list, use the append() method:
Example
thislist.append("orange")
print(thislist)
Output
thislist.insert(1, "orange")
print(thislist)
Output
thislist.remove("banana")
print(thislist)
Output
['apple', 'cherry']
Example
The pop() method removes the specified index, (or the last item if index is not specified):
thislist.pop()
print(thislist)
Output
['apple', 'banana']
Example
del thislist[0]
print(thislist)
Output
['banana', 'cherry']
Example
del thislist
Output
print(thislist) #this will cause an error because you have succsesfully deleted "thislist".
Example
thislist.clear()
print(thislist)
Output
[]
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
mylist = thislist.copy()
print(mylist)
Output
mylist = list(thislist)
print(mylist)
Output
There are several ways to join, or concatenate, two or more lists in Python.
list2 = [1, 2, 3]
print(list3)
Output
Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output
Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output
print(thislist)
Output