Skip to content

Python List

How to create, access, manipulate, and work with Python lists, including indexing, slicing, list comprehension, and common methods for efficient data handling.

Python List is an ordered sequence of elements.

Furthermore:

  • Python lists are mutable, meaning that the value of elements in a list can be changed.
  • It is not necessary that all elements in a list be of the same type.

Create Python Lists

In Python, a list is created by placing elements inside square brackets [], separated by commas.

my_list = [1, 2, 3]

A list can have any number of items and they may be of different types (like integer, float, string, etc.).

my_list = []

my_list = [1, "a string", 2.3]

Lists can be nested (a list can also have another list as an item).

my_list = ["a string", ['nested', 1, 2], [(10,20,30)]]

Access List Elements

There are several ways to access elements in a list.

with List Index

The index operator [] is used to access an element in a list.

  • In Python, the list index starts from 0.
  • The index must be an integer. Using values of any other type will result in a TypeError.
  • Nested lists are accessed using nested indexing.
List Examplespython
my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']

print(my_list[0])  # t

print(my_list[1])  # u

print(my_list[4])  # r

print(my_list[4.0])
Nested List Examplespython
nested_list = ["string", [2, 0, 1, 5]]

print(nested_list[0][1]) # t 
print(nested_list[1][3]) # 5

with Negative List Index

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']

print(my_list[-1]) # l

print(my_list[-4]) # r

Slicing

A range of elements in a list can be accessed using the slicing operator :.

The possible cases (with examples) are shown in the table below:

Slice Description Example with li=[10,20,30,40]
my_list[from:to] the elements from from to to-1 li[1:3] -> [20,30]
my_list[from:] the elements from from to the end of the list li[2:] -> [30,40]
my_list[:to] the elements from the beginning of the list to the element to-1 li[:3] -> [10,20,30]
my_list[:] all elements li[:] -> [10,20,30,40]
my_list[from:to:step] one element each step from from to to-1 li[0:3:2] -> [10,30]
my_list[from::step] one item each step from from until the end of the list li[1::2] -> [20,40]
my_list[:to:step] one element each step from the beginning to the to-1 element. li[:3:2] -> [10,30]
my_list[::step] one item each step li[::2] -> [10,30]

List Manipulation

Lists are mutable, meaning their elements can be changed (unlike string or tuple).

Add List Elements

You can add one item to a list with the append() method or add multiple items with the extend() method.

odd_list = [1, 3, 5]
odd_list.append(7)  # Append item to odd_list
print(odd_list)     # [1, 3, 5, 7]
odd_list.extend([9, 11, 13]) # Append list to odd_list
print(odd_list)     # [1, 3, 5, 7, 9, 11, 13]

As an alternative to the extend() function, the concatenation operator + can be used to combine two lists. Also, using the * operator, elements of a list can be repeated a specific number of times to create a new list.

odd_list = [1, 3, 5]
concat_list = odd_list + [5, 9, 7] # Concat with +
print(concat_list)   # [1, 3, 5, 5, 9, 7]

repeated = ["re"] * 3 # Repeat list three times
print(repeated) # ['re', 're', 're']

In addition, we can insert an element at a desired position using the insert() method or insert multiple elements by compressing them into an empty slice of a list.

odd_list = [1, 9]
odd_list.insert(1,3)
print(odd_list) # [1, 3, 9]
odd_list[2:2] = [5, 7]
print(odd_list) # [1, 3, 5, 7, 9]

Change List Elements

You can use the assignment operator = to modify an element or range of elements.

my_list = [2, 4, 6, 8]
my_list[0] = 1  # change the 1st item 
print(my_list)  # [1, 4, 6, 8]

my_list[1:4] = [3, 5, 7]

print(my_list)  # [1, 3, 5, 7]  

Delete List Elements

You can delete one or more items from a list using Python's del statement. It can also delete the list completely.

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
del my_list[2]   # delete one item
print(my_list)   # ['t', 'u', 'o', 'r', 'i', 'a', 'l']
del my_list[1:5] # delete multiple items
print(my_list)   # ['t', 'a', 'l']
del my_list      # delete the entire list

print(my_list)

The remove() function is used to remove the given element and pop() function is used to remove an element at the given index.

And the clear() function is used to empty the whole list.

my_list = ['t','u','t','o','r','i','a','l']
my_list.remove('t')

print(my_list) # ['u', 't', 'o', 'r', 'i', 'a', 'l']
print(my_list.pop(1)) # t
print(my_list)  # ['u', 'o', 'r', 'i', 'a', 'l']
print(my_list.pop()) # l
print(my_list)  # ['u', 'o', 'r', 'i', 'a']
my_list.clear()
print(my_list)  # []

Finally, you can delete items from a list by assigning an empty list to a slice of items.

my_list = ['t','u','t','o','r','i','a','l']
my_list[4:6] = []
print(my_list) # ['t', 'u', 't', 'o', 'a', 'l']
my_list[2:] = []
print(my_list) # ['t', 'u']

List Comprehension

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by for statement inside square brackets.

For example, make a list with each element multiplied by 10:

mult = [10 * x for x in range(10)]
print(mult)  # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

and this code is equivalent to:

mult = []
for x in range(10):
   mult.append(10 * x)
print(mult)

A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. For example:

pow2 = [2 ** x for x in range(10) if x > 5]
print(pow2)

odd = [x for x in range(10) if x % 2 == 1]
print(odd)

strings = [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
print(strings) # ['Python Language', 'Python Programming', 'C Language', 'C Programming']

Other List Operations

List Membership Test

The keyword in is used to check whether an item exists in a list.

my_list = ['t','u','t','o','r','i','a','l']
 
print('t' in my_list) # True
print('e' in my_list) # False
print('c' not in my_list) # True

Iterating Through a List

Using a for loop, it is possible to iterate each element of a list.

for color in ['red','blue','yellow']:
    print("I'm wearing a", color, "t-shirt")

Output

I'm wearing a red t-shirt
I'm wearing a blue t-shirt
I'm wearing a yellow t-shirt

Summary of Python List Methods

Python has many useful list methods that make it very easy to work with lists.

The following are some of the commonly used list methods.

Method Description
append() adds an element to the end of the list
clear() removes all items from the list
copy() returns a shallow copy of the list
count() returns the count of the number of items passed as an argument
extend() adds all elements of a list to another list
index() returns the index of the first matched item
insert() inserts an item at the defined index
pop() returns and removes an element at the given index
remove() removes an item from the list
reverse() reverse the order of items in the list
sort() sort items in a list in ascending order
Navigation