List in python is a collection of arbitrary objects (compound data types) and often referred to as sequences. List is one of the most frequently used and very versatile data types used in Python. Somewhat similar of characteristics to an array in other programming languages.
With the site we could show you some most common use cases with list in python with practical examples. All examples on this page were tested on both python 3 and python 2. We let you know the result of testing (matching output and actuall output) below each example.
More information about the testing such as python version, actual outputs, date of testing, ... you can find in test report
If you want to contribute more examples, feel free to create a pull-request on Github!
Table of Contents:
- How to create a list?
- List Comprehension: Elegant way to create new List
- List Length/size
- How to add elements to a list?
- How to access elements from a list?
- a. List Index
- b. List negative indexing
- c. How to slice lists in Python?
- d. Check if Item Exists in List
- How to delete or remove elements from a list?
- a. List remove
- b. List pop
- c. List del
- Other List Operations in Python
- a. List Membership Test
- b. Iterating Through a List
- Python List Methods
- a. List append()
- b. List extend()
- c. List insert()
- d. List remove()
- e. List pop()
- f. List clear()
- g. List index()
- h. List count()
- i. List sort()
- j. List reverse()
- k. List copy()
- Built-in functions with List
- a. reduce()
- b. sum()
- c. ord()
- d. cmp()
- e. min()
- f. all()
- g. any()
- h. len()
- i. enumerate()
- j. accumulate()
- k. filter()
- l. map()
- m. lambda()
How to create a list?
A list is created by placing all the items (elements) inside square brackets [], separated by commas. It can
have any number of items and they may be of different types (integer, float, string etc.). It can also have
another list as an item. This is called a nested list.
Example:
my_list = []
my_list = [1, 2, 3]
my_list = ["Hello World", 1.5, 1, -1]
my_list = ["Hello World", ['a', 'b'], 3, [1, 2]]
List Comprehension: Elegant way to create new List
A list comprehension is an elegant, concise way to define and create a list in Python.
Python List Comprehensions consist of square brackets containing an expression, which is executed for each
element in an iterable. Each element can be conditionally included and or transformed by the comprehension.
Create a new list with for loop:
new_list = []
for item in old_list:new_list.append(item)
Create a new list with list comprehension:
new_list = [item for item in old_list]
List Length/size
Python list method len() returns the number of elements in the list.
Example:
my_list = [1, 2, 3]
print('Length of my_list: ')
print(len(my_list))
Output:
Tested:
How to add elements to a list?
Add an element to a list:
Example:
my_list = [1, 2, 3]
my_list.append(4) # Add an element to a list
print(my_list)
Output:
Tested:
How to access elements from a list?
a. List Index
To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index.
Example:
my_list = [1, 2, 3]
#Access the first item in list
print("my_list[0]: " + str(my_list[0]))
Output:
Tested:
b. List negative indexing
The negative indexing starts from where the array ends. This means that the last element of the array is
the first element in the negative indexing which is -1.
Example:
arr = [10, 20, 30, 40, 50]
print (arr[-1])
print (arr[-2])
Output:
Tested:
c. How to slice lists in Python?
In a slicing, the start position start
and end position stop
of the selection
are written as [start:stop]
.
The range start <= x <stop
is selected. Note that the item at start
is
included, but the item at stop
is not included.
Example:
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])
Output:
Tested:
d. Check if Item Exists in List
To check if Python list contains a specific item, use an inbuilt in
operator. The in
operator that checks if the list contains a specific element or not.
It can also check if the item exists on the list or not using for
loop, list.count()
, any
function. But in
operator is most common use.
Using in
Example:
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
# using in
print("Checking if 4 exists in list ( using in ) : ")
if (4 in test_list):
print ("Element Exists")
Output:
Checking if 4 exists in list ( using in ) : Element Exists
Tested:
Using for loop
Example:
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
# using loop
print("Checking if 4 exists in list ( using loop ) : ")
for i in test_list:
if(i == 4) :
print ("Element Exists")
Output:
Checking if 4 exists in list ( using loop ) :
Element Exists
Tested:
Using list count (reference to count
builtin function with list)
Example:
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
# using list count
print("Checking if 4 exists in list ( using list count ) : ")
if test_list.count(4):
print("Element Exists")
Output:
Checking if 4 exists in list ( using list count ) :
Element Exists
Tested:
Using any (reference to any
builtin function with list)
How to delete or remove elements from a list?
a. List remove
The remove() method is one of the most commonly used list object methods to remove an item or an element from the list. When you use this method, you will need to specify the particular item that is to be removed.
Example:
myList = ["Bran", 11, 22, 33, "Stark", 22, 33, 11]
myList.remove(22)
print(myList)
Output:
['Bran', 11, 33, 'Stark', 22, 33, 11]
Tested:
b. List pop
When using the pop(), we specify the index of the item as the argument, and hence, it pops out the item
to be returned at the specified index.
Example:
myList = ["Bran", 11, 22, 33, "Stark", 22, 33, 11]
print(myList.pop(1))
Output:
Tested:
c. List del
The del operator removes the item or an element at the specified index location from the list, but the
removed item is not returned, as it is with the pop() method.
Example:
myList = ["Bran", 11, 22, 33, "Stark", 22, 33, 11]
del myList[2]
print(myList)
Output:
['Bran', 11, 33, 'Stark', 22, 33, 11]
Tested:
Other List Operations in Python
a. List Membership Test
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There
are two membership operators
In - Evaluates to true if it finds a variable in the specified sequence and false otherwise
Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
Output:
Line 1 - a is not available in the given list
Tested:
Not in - Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
Output:
Line 2 - b is not available in the given list
Tested:
b. Iterating Through a List
Using For loop
Example:
list = [1, 3, 5, 7, 9]
for i in list:
print(i)
Output:
Tested:
Python List Methods
a. List append()
Add an element to the end of the list
Example:
my_list = ['items', 'plus']
my_list.append('items')
print (my_list)
Output:
['items', 'plus', 'items']
Tested:
b. List extend()
Add all elements of a list to the another list
Example:
my_list = ['items', 'plus']
another_list = [6, 0, 4, 1]
my_list.extend(another_list)
print (my_list)
Output:
['items', 'plus', 6, 0, 4, 1]
Tested:
c. List insert()
Insert an item at the defined index
Example:
list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
list1.insert(4, 10)
print(list1)
list2 = ['a', 'b', 'c', 'd', 'e']
list2.insert(0, 'z')
print(list2)
Output:
[1, 2, 3, 4, 10, 5, 6, 7]
['z', 'a', 'b', 'c', 'd', 'e']
Tested:
d. List remove()
Removes an item from the list
Example:
list1 = [ 1, 2, 1, 1, 4, 5 ]
list1.remove(1)
print(list1)
list2 = [ 'a', 'b', 'c', 'd' ]
list2.remove('a')
print(list2)
Output:
[2, 1, 1, 4, 5]
['b', 'c', 'd']
Tested:
e. List pop()
Removes and returns an element at the given index
Example:
list1 = [ 1, 2, 3, 4, 5, 6 ]
print(list1.pop())
print("New List after pop : ")
print(list1)
print("\n")
list2 = [1, 2, 3, ('cat', 'bat'), 4]
print(list2.pop())
print(list2.pop())
print(list2.pop())
print("New List after pop : ")
print(list2)
Output:
6
New List after pop :
[1, 2, 3, 4, 5]
4
('cat', 'bat')
3
New List after pop :
[1, 2]
Tested:
f. List clear()
Removes all items from the list
Example:
List = [6, 0, 4, 1]
print('List before clear:', List)
List.clear()
print('List after clear:', List)
Output:
List before clear: [6, 0, 4, 1]
List after clear: []
Tested:
Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method. You can use the
del operator instead.
g. List index()
Returns the index of the first matched item
Example:
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
print(list1.index(4))
list2 = ['cat', 'bat', 'mat', 'cat', 'pet']
print(list2.index('cat'))
Output:
Tested:
h. List count()
Returns the count of number of items passed as an argument
Example:
list1 = [1, 1, 1, 2, 3, 2, 1]
print(list1.count(1))
list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
print(list2.count('b'))
list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat']
print(list3.count('Cat'))
Output:
Tested:
i. List sort()
Sort items in a list in ascending order
Sorting list of Numbers
Example:
numbers = [1, 4, 3, 2]
numbers.sort()
print(numbers)
Output:
Tested:
Sorting list of Strings
Example:
strs = ["python", "code", "ide", "practice"]
strs.sort()
print(strs)
Output:
['code', 'ide', 'practice', 'python']
Tested:
j. List reverse()
Reverse the order of items in the list
Example:
def Reverse(lst):
lst.reverse()
return lst
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
Output:
Tested:
k. List copy()
Returns a shallow copy of the list
Example:
list1 = [ 1, 2, 3, 4 ]
list2 = list1.copy()
print ("The new list created is : " + str(list2))
list2.append(5)
print ("The new list after adding new element : " + str(list2))
print ("The old list : " + str(list1))
Output:
The new list created is : [1, 2, 3, 4]
The new list after adding new element : [1, 2, 3, 4, 5]
The old list : [1, 2, 3, 4]
Tested:
Copy() method is not available in python 2.
Built-in functions with List
a. reduce()
Apply a particular function passed in its argument to all of the list elements stores the intermediate
result and only returns the final summation value
Create Built-in sum() function
Example:
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
def custom_sum(first, second):
return first + second
result = reduce(custom_sum, numbers)
print(result)
Output:
Tested:
Example:
import functools
import operator
lis = [ 1, 2, 5, 6, 3 ]
print ("The sum of the list elements is : ")
print (functools.reduce( operator.add, lis))
print ("The concatenated product is : ")
print (functools.reduce( operator.add,["python", "for", "everyone"]))
Output:
The sum of the list elements is :
17
The concatenated product is :
pythonforeveryone
Tested:
b. sum()
Sums up the numbers in the list
Example:
numbers = [2, 3, 1, 4, 5, 1, 4, 5]
Sum = sum(numbers)
print(Sum)
Sum = sum(numbers, 10)
print(Sum)
Output:
Tested:
c. ord()
Returns an integer representing the Unicode code point of the given Unicode character
Example:
value = ord("a")
value1 = ord("A")
print (value)
print (value1)
Output:
Tested:
d. cmp()
This function returns 1, if first list is “greater” than second list max() return maximum element of
given list in Python 2.x
Example:
a = 1
b = 10
print(cmp(a, b))
a = 5
b = 5
print(cmp(a, b))
a = 6
b = 1
print(cmp(a, b))
Output:
Tested:
cmp() does not work in Python 3.x
e. min()
Return minimum element of given list
Example:
print (min( 3, 12, 23.3, 20, 100 ) )
Output:
Tested:
f. all()
Returns true if all element are true or if list is empty
The 0 (zero) values in lists are considered as false and the non-zero values such as 1, 20 etc are
considered true.
Example:
lis1 = [12, 5, 76, 45]
print(all(lis1))
lis2 = [0, 0, False]
print(all(lis2))
lis3 = [0, 10, 25]
print(all(lis3))
Output:
Tested:
g. any()
Return true if any element of the list is true. If list is empty, return false
Example:
lis1 = [10, 20, 30, 40]
print(any(lis1))
lis2 = [0, False]
print(any(lis2))
lis3 = [0, 10, 5, 15]
print(any(lis3))
Output:
Tested:
h. len()
Returns length of the list or size of the list
Example:
string = "python"
print(len(string))
Output:
Tested:
i. enumerate()
Returns enumerate object of list
Example:
x = ('python', 'is', 'easy')
y = enumerate(x)
print(list(y))
Output:
[(0, 'python'), (1, 'is'), (2, 'easy')]
Tested:
j. accumulate()
Apply a particular function passed in its argument to all of the list elements returns a list containing
the intermediate results
Example:
import itertools
import operator
lis = [1, 2, 3, 4, 5]
result = itertools.accumulate(lis, operator.mul)
for each in result:
print(each)
Output:
Tested:
This method is not available in python 2.
k. filter()
Tests if each element of a list true or not
Example:
ages = [3, 11, 14, 18, 22, 33]
def myFunc(x):
if x < 20:
return False
else:
return True
allowed = filter(myFunc, ages)
for x in allowed:
print(x)
Output:
Tested:
l. map()
Returns a list of the results after applying the given function to each item of a given iterable
Example:
def myfunc(a):
return len(a)
x = map(myfunc, ('python', 'is', 'easy'))
print(list(x))
Output:
Tested:
m. lambda()
This function can have any number of arguments but only one expression, which is evaluated and returned.
Example:
x1 = lambda a, b: a * b
print(x1(5, 7))
x2 = lambda a, b, c: a + b + c
print(x2(5, 6, 7))
Output:
Tested: