Top 25 Questions on Python List

25 questions on lists to enhance your knowledge on python lists.

.Photo by Lalith T on Unsplash

25 Question on Python Lists

Python List:

A list is a data structure in python that is mutable and ordered sequence of elements.
A list is created by placing all items inside the square bracket and separated by commas.

Example: num=[1,2,3]

25 Question on Python Lists

Differences(Image Source: Author)

Image Source: Author

1. Difference between append and extend?

Image Source: Author

append:

num1=[1,2,3]
num2=[4,5,6]
num1.append(num2)
print (num1)
#Output:[1, 2, 3, [4, 5, 6]]

extend:

num1=[1,2,3]
num2=[4,5,6]
num1.extend(num2)
print (num1)
#Output:[1, 2, 3, 4, 5, 6]

2.Difference between del and clear?

Image Source: Author

The del statement

num1=[1,2,3,4,5,6]
#deleting element at index 1
del num1[1]
print(num1)
#Output:[1, 3, 4, 5, 6]
#deleting slice
del num1[2:4]
print (num1)
#Output:[1, 3, 6]
#deleting all the elements from the list
del num1[:]
print (num1)
#Output:[]
#deleting the list itself
del num1
print (num1)
#Output:NameError: name 'num1' is not defined

clear

num1=[1,2,3]
num1.clear()
print (num1)
#Output:[]

3.Difference between remove and pop?

Image Source: Author

remove

num1=[1,2,3,4,5,3]
#Removing element '3' from the list.It will remove only first occurences of that element.
num1.remove(3)
print (num1)#Output:[1, 2, 4, 5, 3]
#If we didn't mention any element,it will raise TypeError.
num1.remove()
#Output:TypeError: remove() takes exactly one argument (0 given)
#If the mentioned element is not in the list,it will raise ValueError.
num1.remove(10)
#Output:ValueError: list.remove(x): x not in list

pop

num1=[1,2,3,4,5]
#removes and returns the last element from the list.
print (num1.pop())#Output:5
print (num1)#Output:[1, 2, 3, 4]
#If index is mentioned,removes and returns the element at the specfied index.
print (num1.pop(3))#Output:4
print (num1)#Output:[1, 2, 3]

4. Difference between indexing and Slicing?

Image Source: Author

Refer to my story of Indexing and Slicing.

Indexing

list_=[10,20,30,40,50]
print (list_[0])#Output:10
print (list_[-1])#Output:50
print (list_[-2])#Output:40

Slicing.

s[1:3]-Returns new list containing elements from index 1 till index 3(excluded)

num=[0,1,2,3,4,5]
print(num[1:3])
#Output:[1, 2]

5. Difference between sort and sorted?

Image Source: Author

sort

a1=[2,4,6,8,0,7,5,3,1]
a1.sort()
print (a1)
'''
Output: 
[0, 1, 2, 3, 4, 5, 6, 7, 8]
'''

sorted()

Refer to my story for sorted function.

a1=[2,4,6,8,0,7,5,3,1]
a2=sorted(a1)
print (f"Original List:{a1}")
print (f"Sorted List:{a2}")
'''
Output:
Original List:[2, 4, 6, 8, 0, 7, 5, 3, 1]
Sorted List:[0, 1, 2, 3, 4, 5, 6, 7, 8]
'''

6. Difference between reverse and reversed?

Image Source: Author

reverse

num1=[1,3,5,7,9]
num1.reverse()
print (num1)
#Output:[9, 7, 5, 3, 1]

reversed

num1=[1,3,5,7,9]
num2=reversed(num1)
print (num2)#Output:<list_reverseiterator object at 0x00ADE4D8>
#Converting iterator object to list using list()
print (list(num2))#Output:[9, 7, 5, 3, 1]

7. Difference between copy and deepcopy?

Image Source: Author

Refer to my story for copy vs deepcopy.

copy

from copy import copy
x=[1,2,[3,4]]
#Copying x
y=copy(x)

#Modifying elemets in the outer list
#Changes are not reflected in the copied list
x[0]=99
print (x)#Output:[99, 2, [3, 4]]
print (y)#Output:[1, 2, [3, 4]]

#Modifying elements in the nested list.
#Changes are reflected in the copied list also.
x[2][0]=5555
print (x)#Output:[99, 2, [5555, 4]]
print (y)#Output:[1, 2, [5555, 4]]

deepcopy

from copy import deepcopy
x=[1,2,[3,4]]
#deepcopying x
y=deepcopy(x)

#Modifying elements in the outer list.
#It is not reflected in the deepcopied list.
x[0]=99
print (x)#Output:[99, 2, [3, 4]]
print (y)#Output:[1, 2, [3, 4]]

#Modifying elements in the nested list.
#It is also not reflected in the deepcopied list.
x[2][0]=555
print (x)#Output:[99, 2, [555, 4]]
print (y)#Output:[1, 2, [3, 4]]

8. How to find the number of elements in the list?

len() — len function returns the number of elements in the list.

Example:

num1=[1,2,3,4]
print (len(num1))
#Output:4

9. How to find the largest and lowest value in the list?

min() -returns the largest value in a list of values.
max()– return the lowest value in a list of values.

num1=[1,2,3,4]
print (min(num1))#Output:1
print (max(num1))#Output:4

num2=['red','blue','green']
print (min(num2))#Output:blue
print (max(num2))#Output:red

10. How to check whether the list is empty or not?

We can check by the below mentioned three methods.

  • len()-If length is zero means list is empty
num1=[]
print (len(num1))#Output:0
  • if not list:
num1=[]
if not num1:
    print ("list is empty")
#Output:list is empty
  • compare against the empty list
num1=[]
num2=[]
if num1==num2:
    print ("list is empty")

#Output:list is empty

11. How to find the first and last element of the list?

Using Indexing, we can find the first and last element of the list.

num[0]-returns first element

num[-1]-returns last element

num=[1,2,3,4,5]
#returns first element
print (num[0])#Output:1
#returns last element
print (num[-1])#Output:5

12. How to access elements of the list?

  • Using Indexing
    By using indexing, we can access the element in that particular index.
  • Using for loop.
    Using for loop, we can iterate through the list.
num=[1,2,3,4,5]
#Accessing second element
print (num[1])#Output:1
#for loop
for i in num:
    print (i)
#Output:
'''
1
2
3
4
5
'''

13. How to modify elements of the list?

Lists in Python are mutable. We can modify the items in the list by using indexing, slicing.

Modifying a particular element using Indexing.

Image Source: Author
num=[1,2]
num[0]=22
print (num)
#Output:[22, 2]

Modifying the sequence of elements using Slicing.

Image Source: Author
num=[1,2,3,4,5]
num[1:3]=[11,22]
print (num)
#Output:[1, 11, 22, 4, 5]

14. How to concatenate two lists?

  • Using + operator.

Using + operator, we can join two or more lists

num1=[1,2]
num2=[3,4]
num3=[5,6]
print (num1+num2+num3)
#Output:[1, 2, 3, 4, 5, 6]

15. How to add two lists element-wise in python?

  • Using zip() in for loop

zip(*iterables)-zip function will pair elements from the same position in the iterables.

num1=[1,2,3]
num2=[4,5,6]
num3=[]
for i,j in zip(num1,num2):
    num3.append(i+j)
print (num3)
#Output:[5, 7, 9]
  • Using zip() in a list comprehension
num1=[1,2,3]
num2=[4,5,6]
num3=[i+j for i,j in zip(num1,num2)]
print (num3)
#Output:[5, 7, 9]

Refer to my story for list comprehension

16. How to remove duplicate elements in the list?

Set don’t contain duplicate elements in python. We can convert the list to set by using the set() constructor and converts back to the list using the list() constructor.

num1=[1,2,3,1,2,3,4,3,2,5,4,3]
num2=set(num1)
print (list(num2))
#Output:[1, 2, 3, 4, 5]

17. How to find the occurrences of an element in the python list?

count()

count() method will return the number of occurrences of a particular element mentioned.

a1=[1,2,3,4,1,5,6,1]
print (a1.count(1))
#Output:3

18. How to find an index of an element in the python list?

index()

index(i) method will return the index of the first item whose value is equal to i

n=[1,2,3,4,5]
print (n.index(2))
#Output:1

19. How to check if an item is in the list?

Can be done by membership test.

in and not in operations are used only for simple containment testing.

n=[1,2,3,4,5]
if 1 in n:
 print ("yes")
if 2 not in n:
 print ("no")
#Output:yes

20. How to insert an item at a given position?

We can insert an item at a given position using the insert method.

list.insert(i,x)

i-index(at which position we have to insert)
x-element(what element needs to be inserted)

n=[1,2,3,4,5]
#inserting element 99 at index 1
n.insert(1,99)
print (n)
#Output:[1, 99, 2, 3, 4, 5]

21. How to flatten a list in python?

Method 1: List comprehension using two for clause.

n=[[1,2,3],[4,5,6],[7,8,9]]
n1=[num2 for num1 in n for num2 in num1]
print (n1) #Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

Method 2:Using for loop

n1=[[1,2,3],[4,5,6],[7,8,9]]
n2=[]
for num1 in n1:
for num2 in num1:
  n2.append(num2)
print (n2) #Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

Method3: Using chain.from_iterable():

itertools.chain.from_iterable():
This function takes one iterable as an input argument and returns a flattened iterable containing all elements in the input iterable. All elements in the input iterable should be iterable, otherwise, it will raise TypeError.

chain.from_iterable(iterable)

import itertools
n1=itertools.chain.from_iterable([[1,2,3],[4,5,6],[7,8,9]])
#returns an itertools.chain object
print (n1)
#Output:<itertools.chain object at 0x0282E4D8>
#converting an iterator to list object using list() constructor.
print (list(n1))
#Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

22. How to convert python list to other data structures like set, tuple, dictionary?

  • Converting a list to set using set() constructor.
    Set don’t contain duplicate elements. So if we convert a list to set, duplicates will be removed.
n1=[1,2,3,4,2,3]
s1=set(n1)
print (s1)
#Output:{1, 2, 3, 4}
  • Converting a list to a tuple using a tuple() constructor.
n1=[1,2,3,4,2,3]
t1=tuple(n1)
print (t1)
#Output:(1, 2, 3, 4, 2, 3)
  • Converting a list to a dictionary.

i)Converting a list of tuples to a dictionary using dict() constructor.

n1=[(0,1),(2,3),(4,5)]
d1=dict(n1)
print (d1)
#Output:{0: 1, 2: 3, 4: 5}

ii)Converting a list to a dictionary using the fromkeys() method.

fromkeys()
Create a new dictionary with keys from iterable and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.

fromkeys(iterable,value)

#fromkeys() method returns a dictionary with the specified keys and the specified value.
a={'a','e','i','o','u'}
b='vowels'
d1=dict.fromkeys(a,b)
print(d1)
#Output: {'o': 'vowels', 'u': 'vowels', 'e': 'vowels', 'i': 'vowels', 'a': 'vowels'}
#dictionary is unordered.


#if value is not mentioned,it defaults to None.
d2=dict.fromkeys(a)
print (d2)
#Output:{'e': None, 'a': None, 'u': None, 'i': None, 'o': None}

23. How to apply a function to all items in the list?

We can use a map() function to apply a function to all items in the list.

Refer to my story of map() vs starmap()

map(function, iterable...)

Return an iterator that applies a function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.

Example: Finding square of all numbers in the list.

Applying a square function to list using a map() function.

n1=[1,2,3,4,5]

def square(n):
return n*n

n2=map(square,n1)
print (n2)
#output:<map object at 0x00D6EC10>
#converting map object to list using list() constructor.
print (list(n2))
#Output:[1, 4, 9, 16, 25]

24. How to filter the elements based on a function in a python list?

We can use filter() to filter the elements in the list based on some function.

Refer to my story of filter vs filterfalse

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Example: Filter the odd numbers in the given list.

n1=[1,2,3,4,5]

def odd(n):
if n%2!=0:
return True

n2=filter(odd,n1)
print (n2)
#output:<filter object at 0x00F3EC10>
#converting filter object to list using list() constructor.
print (list(n2))
#Output:[1,3,5]

25. How python lists are stored in memory?

Instead of storing values in memory space, Python lists store references/pointers to the values (object).

Image Source: Author

My other blog links

15 Things to Know to Master Python Dictionaries


Resources(Python Documentation):

Lists

More On Lists

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s