PythonList Using python list with examples.

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:

  1. How to create a list?
  2. List Comprehension: Elegant way to create new List
  3. List Length/size
  4. How to add elements to a list?
  5. 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
  6. How to delete or remove elements from a list?
    • a. List remove
    • b. List pop
    • c. List del
  7. Other List Operations in Python
    • a. List Membership Test
    • b. Iterating Through a List
  8. 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()
  9. 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:
# empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed data types my_list = ["Hello World", 1.5, 1, -1] # nested list 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:
Length of my_list: 3
Tested:
Python 3 Passed
Python 2 Passed

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:
[1, 2, 3, 4]
Tested:
Python 3 Passed
Python 2 Passed

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:
my_list[0]: 1
Tested:
Python 3 Passed
Python 2 Passed

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:
50 40
Tested:
Python 3 Passed
Python 2 Passed

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:
[10, 20, 30, 40]
Tested:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
11
Tested:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

b. Iterating Through a List

Using For loop

Example:
list = [1, 3, 5, 7, 9] # Using for loop for i in list: print(i)
Output:
1 3 5 7 9
Tested:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

c. List insert()

Insert an item at the defined index

Example:
list1 = [ 1, 2, 3, 4, 5, 6, 7 ] # insert 10 at 4th index list1.insert(4, 10) print(list1) list2 = ['a', 'b', 'c', 'd', 'e'] # insert z at the front of the list list2.insert(0, 'z') print(list2)
Output:
[1, 2, 3, 4, 10, 5, 6, 7] ['z', 'a', 'b', 'c', 'd', 'e']
Tested:
Python 3 Passed
Python 2 Passed

d. List remove()

Removes an item from the list

Example:
# the first occurrence of 1 is removed from the list list1 = [ 1, 2, 1, 1, 4, 5 ] list1.remove(1) print(list1) # removes 'a' from list2 list2 = [ 'a', 'b', 'c', 'd' ] list2.remove('a') print(list2)
Output:
[2, 1, 1, 4, 5] ['b', 'c', 'd']
Tested:
Python 3 Passed
Python 2 Passed

e. List pop()

Removes and returns an element at the given index

Example:
list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last element from the list print(list1.pop()) # Print list after removing last element print("New List after pop : ") print(list1) print("\n") list2 = [1, 2, 3, ('cat', 'bat'), 4] # Pop last three element print(list2.pop()) print(list2.pop()) print(list2.pop()) # Print list 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:
Python 3 Passed
Python 2 Passed

f. List clear()

Removes all items from the list

Example:
# Creating list List = [6, 0, 4, 1] print('List before clear:', List) # Clearing list List.clear() print('List after clear:', List)
Output:
List before clear: [6, 0, 4, 1] List after clear: []
Tested:
Python 3 Passed
Python 2 Failed

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] # Will print the index of '4' in list1 print(list1.index(4)) list2 = ['cat', 'bat', 'mat', 'cat', 'pet'] # Will print the index of 'cat' in list2 print(list2.index('cat'))
Output:
3 0
Tested:
Python 3 Passed
Python 2 Passed

h. List count()

Returns the count of number of items passed as an argument

Example:
list1 = [1, 1, 1, 2, 3, 2, 1] # Counts the number of times 1 appears in list1 print(list1.count(1)) list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b'] # Counts the number of times 'b' appears in list2 print(list2.count('b')) list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat'] # Counts the number of times 'Cat' appears in list3 print(list3.count('Cat'))
Output:
4 3 2
Tested:
Python 3 Passed
Python 2 Passed

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:
[1, 2, 3, 4]
Tested:
Python 3 Passed
Python 2 Passed

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:
[15, 14, 13, 12, 11, 10]
Tested:
Python 3 Passed
Python 2 Passed

k. List copy()

Returns a shallow copy of the list

Example:
# Initializing list list1 = [ 1, 2, 3, 4 ] # Using copy() to create a shallow copy list2 = list1.copy() # Printing new list print ("The new list created is : " + str(list2)) # Adding new element to new list 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:
Python 3 Passed
Python 2 Failed

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:
68
Tested:
Python 3 Passed
Python 2 Passed

Using Operator Function

Example:
# importing functools for reduce() import functools # importing operator for operator functions import operator # initializing list lis = [ 1, 2, 5, 6, 3 ] # using reduce to compute sum of list # using operator functions print ("The sum of the list elements is : ") print (functools.reduce( operator.add, lis)) # using reduce to concatenate string 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:
Python 3 Passed
Python 2 Passed

b. sum()

Sums up the numbers in the list

Example:
numbers = [2, 3, 1, 4, 5, 1, 4, 5] # start parameter is not provided Sum = sum(numbers) print(Sum) # start = 10 Sum = sum(numbers, 10) print(Sum)
Output:
25 35
Tested:
Python 3 Passed
Python 2 Passed

c. ord()

Returns an integer representing the Unicode code point of the given Unicode character

Example:
# inbuilt function return an # integer representing the Unicode code value = ord("a") value1 = ord("A") # prints the unicode value print (value) print (value1)
Output:
97 65
Tested:
Python 3 Passed
Python 2 Passed

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:
# when a<b a = 1 b = 10 print(cmp(a, b)) # when a = b a = 5 b = 5 print(cmp(a, b)) # when a>b a = 6 b = 1 print(cmp(a, b))
Output:
-1 0 1
Tested:
Python 3 Failed
Python 2 Passed

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:
3
Tested:
Python 3 Passed
Python 2 Passed

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:
# all values of this list are true # non-zero values are considered true lis1 = [12, 5, 76, 45] print(all(lis1)) # all values are false # 0 is considered as false lis2 = [0, 0, False] print(all(lis2)) # one value is false, others are true lis3 = [0, 10, 25] print(all(lis3))
Output:
True False False
Tested:
Python 3 Passed
Python 2 Passed

g. any()

Return true if any element of the list is true. If list is empty, return false

Example:
# all values are true lis1 = [10, 20, 30, 40] print(any(lis1)) # all values are false lis2 = [0, False] print(any(lis2)) # one value is false, others are true lis3 = [0, 10, 5, 15] print(any(lis3))
Output:
True False True
Tested:
Python 3 Passed
Python 2 Passed

h. len()

Returns length of the list or size of the list

Example:
string = "python" print(len(string))
Output:
6
Tested:
Python 3 Passed
Python 2 Passed

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:
Python 3 Passed
Python 2 Passed

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 the itertool module import itertools # import operator to work import operator # creating a list lis = [1, 2, 3, 4, 5] # using the itertools.accumulate() result = itertools.accumulate(lis, operator.mul) # printing each item from list for each in result: print(each)
Output:
1 2 6 24 120
Tested:
Python 3 Passed
Python 2 Failed

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:
22 33
Tested:
Python 3 Passed
Python 2 Passed

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:
[6, 2, 4]
Tested:
Python 3 Passed
Python 2 Passed

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:
35 18
Tested:
Python 3 Passed
Python 2 Passed