Python Lists with Examples

FREE Online Courses: Click for Success, Learn for Free - Start Now!

There are many situations where we need to store a couple of values under a single name and use or modify them in the future. In Python, this is done using lists. Here we will discuss Python lists and their operations, built-in methods, etc. So, let’s not wait and start!

Lists in Python

Lists in Python of containers of values of different data types in contiguous blocks of memory. A list can have any data type, including list, tuples, etc., as its element.

Creating lists in Python

We can create a list like we create any other variable, by equating the elements to a variable name on the right using the ’=’ operator. The elements of a list are enclosed with square brackets and the values are separated by using commas.

We can check the data type of a variable using the function ‘type()’. Let’s see an example of creating lists and checking their type.

Example of creating a list:

list1=[] #creating an empty list
print("The data type of",list1,"is:",type(list1))

list2=[1,2,3,4,5] #creating a list of integer values
print("Data type of",list2,"is:",type(list2))

list3=["PythonGeeks", 4,8.9,['a','c'],'h'] #creating a list of values of different data types
print("The data type of",list3,"is:",type(list3))

Output:

The data type of [] is: <class ‘list’>

Data type of [1, 2, 3, 4, 5] is: <class ‘list’>

The data type of [‘PythonGeeks’, 4, 8.9, [‘a’, ‘c’], ‘h’] is: <class ‘list’>

Accessing elements

We can access the elements of a list using indexing. An important point to remember here is that the index starts from ‘0’ not ‘1’. So the first element has an index of 0. We will discuss the

1. Accessing complete list:

We can access the complete list by just using the variable name storing that list. For example,

Example of accessing entire list:

list_1=['a',4,7,0.9,'h',6.5,(5,6),['s','r']]
print(list_1) #printing the entire list

Output:

[‘a’, 4, 7, 0.9, ‘h’, 6.5, (5, 6), [‘s’, ‘r’]]

2. Accessing an element from a list:

We can access an element of a list using the index. For example, to access the first element from a list named ‘list1’, we can print list1[0].

We can also use negative indexing. In Python, the rightmost element of a list has ‘-1’ as the index and it reduces as we move to the left. The figure below depicts this.

Example of accessing an element of a list:

print(list_1[2]) # accessing the 3rd element

print(list_1[-2]) # printing the last 2nd element

Output:

7

(5, 6)

We can also check the type of one of the elements using the index

Python Lists

Example of checking the type of accessed element:

print(type(list_1[-1])) #checking type of the last element

Output:

<class ‘list’>

However, if we exceed the limit of the array size we get an error. It should be less than the length of the list. Even there is a limit on negative indexes. It should not be less than the negative length of the list.

We also get an error if we give the index as any other value than an integer, as indexes are integers only.

Example of getting an error on wrong indexing :

print(list_1[8]) #the index should be less than 8, the length of the list

print(list_1[-9]) #the index should be more than -8, -ve of the length of list

Output:

Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
print(list_1[8]) #the index should be less than 8, the length of list
IndexError: list index out of range
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
print(list_1[-9]) #the index should be more than -8, -ve of the length of list
IndexError: list index out of range

3. Slicing a Python list:

We can access more than one element from a list again using indexing. These indexes can be positive or negative.

a. If we want to access all the elements from ‘ith’ index to ‘jth’, jth exclusive, then we give indexing as ‘i:j’
b. If we want to access all the elements from the ‘ith’ index then we give ‘i:’
c. If we want to access all the elements before the ‘ith’ element, then we give ‘: i’
d. If we want to access all the elements then we can give ‘:’

Example of Python list slicing:

list_1=['a',5,9.0,"PythonGeeks",8,5.6]

print("list_1[1:5] =",list_1[1:5]) # slicing 2nd to 5th element

print("list_1[-4:-1] =",list_1[-4:-1]) # slicing last 4th to 2nd element

print("list_1[:] =",list_1[:]) # getting entire list

print("list_1[4:] =",list_1[4:]) # slicing all elements from 5th one

print("list_1[-3:] =",list_1[-3:]) # slicing all elements after last 3rd one

print("list_1[:2] =",list_1[:3]) # slicing all elements till 3rd one

print("list_1[:-2] =",list_1[:-4])# slicing all elements till last 4th one

Output:

list_1[1:5] = [5, 9.0, ‘PythonGeeks’, 8]

list_1[-4:-1] = [9.0, ‘PythonGeeks’, 8]

list_1[:] = [‘a’, 5, 9.0, ‘PythonGeeks’, 8, 5.6]

list_1[4:] = [8, 5.6]

list_1[-3:] = [‘PythonGeeks’, 8, 5.6]

list_1[:2] = [‘a’, 5, 9.0]

list_1[:-2] = [‘a’, 5]

We can also use a combination of positive and negative indexes. And we can access the elements from ‘ith’ to ‘jth’ index with steps as ‘k’, then we can give the index as ‘i:j:k’. For example,

Example of slicing in Python:

print("list_1[1:-3]=",list_1[1:-3]) #printing all the elements from 2nd to last 3rd one

print("list_1[1:5:2]=",list_1[1:5:2]) #printing from 2nd to 5th elements with the step 2

print("list_1[::3]=",list_1[::3]) #printing all the elements at the interval 3

Output:

list_1[1:-3]= [5, 9.0]

list_1[1:5:2]= [5, ‘PythonGeeks’]

list_1[::3]= [‘a’, ‘PythonGeeks’]

Reassigning the values

We can change a value, a set of values using the indexing. The same rule applies here on the limit of indexing. It should be less than the length of the list and should not be less than the negative of the length of the list.

We can change the entire list too. Examples of reassigning are given below.

Example of reassigning:

list1=[1,2,'u','r',5.6]

list1[1]=1.2 # reassigning the 2nd element
print(list1)

list1[2:4]=['l',3] #reassigning the elements from 3rd to 4th index
print(list1)

list1[3:3]='5'# reassigning the 4th element
print(list1)

list1=[1,2,34,5,8] #reassigning the whole list
print(list1)

Output:

[1, 1.2, ‘u’, ‘r’, 5.6]

[1, 1.2, ‘l’, 3, 5.6]

[1, 1.2, ‘l’, ‘5’, 3, 5.6]

[1, 2, 34, 5, 8]

Deleting the values

We can delete the values of the list using the ‘del’ operator. We can delete a value or a set of values using indexing. And to delete the entire list, we just need its name. Once a list is deleted we cannot access it again, we get NameError.

Example of deleting values and the list itself:

list1=[12,5,'abc',32.4,4.5,"Python"]

del list1[2] #deleting the 3rd element
print(list1)

del list1[1:4] #deleting 2nd to 4th elements
print(list1)

del list1 #deleting the list
print(list1)

Output:

[12, 5, 32.4, 4.5, ‘Python’]

[12, ‘Python’]

Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
print(list1)
NameError: name ‘list1’ is not defined

Multidimensional list in Python

Multidimensional lists are lists that have inner lists inside them. It is a similar concept of the dimension of space. If the list had a list, then it is said to be 2 dimensional. If it has a list of lists, then it is 3 dimensional, and so on.

Example of creating multidimensional list:

m_list=[[1,2,3,4],['a','b','c'],[4.5,6.7,1.3]] #2d list
print(m_list)

print(type(m_list))
[[1, 2, 3, 4], ['a', 'b', 'c'], [4.5, 6.7, 1.3]]

<class 'list'>

Accessing values in a multidimensional list

We can use indexes here too for accessing the elements. For example, to access the 2nd element of the 1st inner list inside the main list named m_list, we can use m_list[0][1].

Example of accessing elements of a multidimensional list:

print(m_list[0][1])#accessing the 2nd element of the 1st inner list

Output:

2

Here 0 is the index of the inner list and 1 is the index of the value inside the inner list that we want to access.

Operations on lists in Python

There are operations that we can perform on lists like concatenation, multiplication, etc. We will discuss this in this section, the effect of these operations on the following two lists.

list1=[1,2,4]
list2=['a','b','v']

Operations on lists in Python

1. Concatenation

We can concatenate two lists using the ‘+’ operator. This will add the elements of the 2nd list at the end of the 1st one. We can do this with more than two lists.

Example of concatenation of lists:

print("Concatenation:",list1+list2)

Output:

Concatenation: [1, 2, 4, ‘a’, ‘b’, ‘v’]

2. Multiplication

Multiplication is not the same as multiplication of numbers. Here on multiplying a list by a number ‘n’, the same list gets added to itself, repeating it ‘n’ times. Here ‘n’ should be a positive integer.

Example of multiplication of a list by a number:

print("Multiplication:",list2*3)

Output:

Multiplication: [‘a’, ‘b’, ‘v’, ‘a’, ‘b’, ‘v’, ‘a’, ‘b’, ‘v’]

3. Membership

The operators ‘in’ and ‘not in’ are the operators used to check the membership of a value in the list. The ‘in’ returns True if the value is in the list else False. The ‘not in’ does the opposite.

Example of membership operation on lists:

print(4 in list1) #checking if 4 is in list1

print('b' not in list2) #checking is 'b' is not there in list2

print('1' in list1) #checking if '1' is there in list1

Output:

True

False

False

4. Iteration

Iteration is the process of going through each element of the list. The most common approach is to use the ‘for loop’. A variable is used as an iterator to go through the list till it reaches the end/empty value. The code to iteration is given below.

Example of iteration in list:

for value in list2: #iteration
  print(value,end=" ")

Output:

a b v

Here, value is the iterator that goes through an element of the list at every loop and prints the elements of the list.

Built-in method on lists in Python

There are many methods predefined in Python to modify the lists. We will see the effect of the most common ones discussed below on the following lists:

List:

list1=[3,6.7,'t',"PythonGeeks",5.9]

a. append(): This method is used to add the element passed to add at the end of the list

Example of applying append () :

list1.append(17)
print(list1)

Output:

[3, 6.7, ‘t’, ‘PythonGeeks’, 5.9, 17]

b. extend(): This function is used to add a list of elements to the existing list.

Example of applying extend() :

list1.extend([2,8.0,'l'])
print(list1)

Output:

[3, 6.7, ‘t’, ‘PythonGeeks’, 5.9, 17, 2, 8.0, ‘l’]

c. insert(): This function is used to add the element at the specified location

Example of applying insert() :

list1.insert(2,3) #inserting 3 at 2nd index or 3rd position
print(list1)

Output:

[3, 6.7, 3, ‘t’, ‘PythonGeeks’, 5.9, 17, 2, 8.0, ‘l’]

d. pop(): This deletes the last element at the specified index and if no index specified it deletes the last value.

Example of applying pop () :

list1.pop()
print(list1)

list1.pop(1)
print(list1)

Output:

‘l’

[3, 6.7, 3, ‘t’, ‘PythonGeeks’, 5.9, 17, 2, 8.0]

6.7

[3, 3, ‘t’, ‘PythonGeeks’, 5.9, 17, 2, 8.0]

e. remove (): This function removes the first occurrence of the value given as an argument

Example of applying remove () :

list1.remove(3)
print(list1)

Output:

[3, ‘t’, ‘PythonGeeks’, 5.9, 17, 2, 8.0]

f. index (): This function returns the index of the value that first matches the value.

Example of applying index () :

list1.index("PythonGeeks")

Output:

2

g. count(): This function returns the number of occurrences of a value. And if it doesn’t exist in the list, it returns 0.

Example of applying count () :

list1.count('t')

list1.count(0)

Output:

1

0

h. sort(): This function is used to sort the values of the list with elements of the same data type.

Example of applying sort () :

list2=[1,6,2,19,5]
list2.sort()
print(list2)

Output:

[1, 2, 5, 6, 19]

i. reverse (): This function is used to reverse all the elements of the list

Example of applying reverse () :

list1.reverse()
print(list1)

Output:

[8.0, 2, 17, 5.9, ‘PythonGeeks’, ‘t’, 3]

j. clear (): This is used to delete all the elements of the list. After this function is applied, the list still exists and is accessible, but it will be empty.

Example of applying clear () :

list1.clear()
print(list1)

Output:

[]

Built-in functions in Python

These are the functions that can be used to get some information from the list like min(), len(), etc. We will discuss each of the functions and their effects on the list.

Built-in functions on Lists

1. len(): This function is used to find the length of the list

Example of applying len() :

list1=[1,5,2,19,34,23]
print(len(list1))

Output:

6

2. min(): This function returns the minimum value of the list

Example of applying min() :

list1=[1,5,2,19,34,23]
print(min(list1))

Output:

1

We can apply this function only on the homogeneous lists, where we can compare the values.

Example of getting an error on applying min() on lists of different data type s:

list2=[1,3.4,'a',5]
print(min(list2))

Output:

Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
print(min(list2))
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’

3. max(): This function outputs the maximum value of the list.

Example of applying max () :

print(max(list1))

Output:

34

This function can be applied only if the elements of the list are of the same data type to be able to compare them.

Example of getting an error on applying max() on lists of different data type s:

list2=[1,3.4,'a',5]
print(max(list2))

Output:

Traceback (most recent call last):
File “<pyshell#2>”, line 1, in <module>
print(max(list2))
TypeError: ‘>’ not supported between instances of ‘str’ and ‘float’

4. sorted (): This function sorts the given list and returns it, but does not change the original one.

Example of applying sorted () :

list1=[1,5,2,19,34,23]
print(sorted(list1))

print(list1)

Output:

[1, 2, 5, 19, 23, 34]

[1, 5, 2, 19, 34, 23]

Again for the same reason, we can apply this function only on homogeneous lists.

5. list(): This function is used to convert the other data types to list.

Example of doing data conversion using list() :

list3=list("zyx")
print(list3)

Output:

[‘z’, ‘y’, ‘x’]

However, we cannot convert a single integer to a list because we cannot iterate over a list.

Example of getting an error on converting a single int to a list:

list4=list(4)

Output:
Traceback (most recent call last):
File “<pyshell#9>”, line 1, in <module>
list4=list(4)
TypeError: ‘int’ object is not iterable

6. sum(): This returns the sum of all the values of the list holding integers.

Example of adding all the elements using sum():

But we cannot do a sum on a list with other data types as they cannot be added. For example,

Example of getting an error on doing sum on list with string values:

list1=[1,5,2,19,34,23]
print(sum(list1))

Output:

84

7. any(): This function returns True if any of the elements is not empty or 0 else False

Example of using any() on list:

print(any(['',0,'',6]))

print(any(['','','',0]))

Output:

True

False

8. all(): This function returns True if and only if all the elements of the list are not empty or 0. If any of the values is empty or 0, it gives False.

Example of using all() function:

print(all(['',4,5,'a']))

print(all([1,2,3,4,5]))

Output:

False

True

List compressions in Python

List compressions are the way to create a list by writing an expression with a condition in a single line enclosed in the square brackets. For further understanding, look at the below example.

Example of creating a list compression:

multiples_3=[3*i for i in range(1,11)]
print(multiples_3)

Output:

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

We can create the same list using the condition as shown below.

Example of creating a list compression with a condition:

mult_3=[i for i in range(1,31) if i%3==0]
print(mult_3)

Output:

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Interview Questions on Lists in Python

Q1. Write a program to print all the alternate elements in reverse order using slicing.

Ans. We can give the start as -1 and the end as 0. And step as 2 to get the alternate values.

Example of slicing in python:

list=[1,2,3,4,5,6,7,8,9,10]
print(list[-1:0:-2])

Output:

[10, 8, 6, 4, 2]

Q2. Write a 2D list with 4 lists in it and print the last element of the 3rd inner list without using negative indexing.

Ans: We can get the index of the last element of the list by doing (length of the list -1).

Example of multi dimensional list in Python:

list=[[1,2,3,4],['a','b','c'],[3.4,5.6,7.8,9.0],[56,'a',3.2]]
last=len(list[2])-1
print(list[2][last])

Output:

9.0

Q3. Show the difference between append and extend using coding.

Ans. Extend adds the elements of the list as the values of the original list. Append considers the whole addition as one value and adds to the list. For a further understanding look at the below code.

Example of showing difference between append() and extend():

list1=[1,2,3,4,5]
list2=['a','b']

list1.append(list2)
print(list1)

list1=[1,2,3,4,5]
list1.extend(list2)
print(list1)

Output:

[1, 2, 3, 4, 5, [‘a’, ‘b’]]

[1, 2, 3, 4, 5, ‘a’, ‘b’]

Q4. Remove all the duplicates from the list without using looping.

Ans. We can do this by converting the list into a set and back to the list. As the set does not access duplicate values, it removes them.

Example to remove duplicates in Python

list1=[1,2,3,1,2,4,5]
set1=set(list1)
list1=list(set1)
print(list1)

Output:

[1, 2, 3, 4, 5]

Q5. Multiply every element of a list by 2 using list comprehension

Ans. Below is the Example of modifying list using list comprehension in Python:

list1=[1,2,3,4,5]
[i*2 for i in list1]

Output:

[2, 4, 6, 8, 10]

Quiz on Python Lists

Conclusion

In this article, we learned about lists, their properties. We also learned about built-in functions and methods to modify and access the list elements. In the end, we saw how to use list comprehensions and solved some interview questions.
Hope you gained your knowledge reading this article. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *