Python List

Python lists store multiple data together in a single variable.

Suppose, we need to store the age of 5 students, instead of creating 5 separate variables, we can simply create a list:

List with 5 Elements
List with 5 elements

Create a Python List

We create a list by placing elements inside square brackets [], separated by commas. For example,

 # a list of three elements
ages = [19, 26, 29]
print(ages)

# Output: [19, 26, 29]

Here, the ages list has three items.

More on List Creation

Here are the different types of lists we can create in Python.

Empty List

# create an empty list
empty_list = []
print(empty_list)

# Output: []

List of different data types

# list of string types
names = ['James', 'Jack', 'Eva']
print (names)

# list of float types
float_values = [1.2, 3.4, 2.1]
print(float_values)

List of mixed data types

# list including string and integer
student = ['Jack', 32, 'Computer Science']
print(student)

# Output: ['Jack', 32, 'Computer Science']

Access List Elements

Each element in a list is associated with a number, known as a list index.

The index always starts from 0, meaning the first element of a list is at index 0, the second element is at index 1, and so on.

Index of List Elements
Index of List Elements

Access Elements Using Index

We use index numbers to access list elements. For example,

languages = ['Python', 'Swift', 'C++']

# access the first element
print(languages[0])   # Python

# access the third element
print(languages[2])   # C++
Access List Elements
Access List Elements

More on Accessing List Elements

Negative Indexing in Python

Python also allows negative indexing. The negative index always starts from -1, meaning the last element of a list is at index -1, the second-last element is at index -2, and so on.

Python Negative Indexing
Python Negative Indexing

Negative index numbers make it easy to access list items from last.

Let's see an example,

languages = ['Python', 'Swift', 'C++']

# access item at index 0
print(languages[-1])   # C++

# access item at index 2
print(languages[-3])   # Python

Note: If the specified index does not exist in a list, Python throws the IndexError exception.

Slicing of a List in Python

In Python, it is possible to access a section of items from the list using the slicing operator :. For example,

my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']

# items from index 2 to index 4
print(my_list[2:5])

# items from index 5 to end
print(my_list[5:])

# items beginning to end
print(my_list[:])

Output

['o', 'g', 'r']
['a', 'm']
['p', 'r', 'o', 'g', 'r', 'a', 'm']

To learn more about slicing in Python, visit Python program to slice lists.


Add Elements to a Python List

We use the append() method to add elements to the end of a Python list. For example,

fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)

# using append method fruits.append('cherry')
print('Updated List:', fruits)

Output

Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'orange', 'cherry']
Add Element at Specific Index

The insert() method adds an element to the specified index of the list. For example,

fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits) 

# insert 'cherry' at index 2 fruits.insert(2, 'cherry')
print("Updated List:", fruits)

Output

Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
Add Elements to a List From Other Iterables

We use the extend() method to add elements to a list from other iterables. For example,

odd_numbers = [1, 3, 5]
print('Odd Numbers:', odd_numbers)

even_numbers  = [2, 4, 6]
print('Even Numbers:', even_numbers)

# adding elements of one list to another odd_numbers.extend(even_numbers)
print('Numbers:', odd_numbers)

Output

Odd Numbers: [1, 3, 5]
Even Numbers: [2, 4, 6]
Numbers: [1, 3, 5, 2, 4, 6]

Here, we have added all the elements of even_numbers to odd_numbers.


Change List Items

We can change the items of a list by assigning new values using the = operator. For example,

colors = ['Red', 'Black', 'Green']
print('Original List:', colors)

# changing the third item to 'Blue' colors[2] = 'Blue'
print('Updated List:', colors)

Output

Original List: ['Red', 'Black', 'Green']
Updated List: ['Red', 'Black', 'Blue']

Here, we have replaced the element at index 2: 'Green' with 'Blue'.

Note: Unlike Python tuples, lists are mutable, meaning we can change the items in the list.


Remove an Item From a List

We can remove an item from a list using the remove() method. For example,

numbers = [2,4,7,9]

# remove 4 from the list numbers.remove(4)
print(numbers) # Output: [2, 7, 9]
Remove One or More Elements of a List

The del statement removes one or more items from a list. For example,

names = ['John', 'Eva', 'Laura', 'Nick']

# deleting the second item
del names[1]
print(names)

# deleting the first item 
del names[0:1]
print(names)

Output

['John', 'Laura', 'Nick']
['Laura', 'Nick']

Note: We can also delete the entire list by using the del statement. For example,

names = ['John', 'Eva', 'Laura', 'Nick']

# deleting the entire list
del names

Python List Length

We use the len() method to find the number of elements present in a list. For example,

cars = ['BMW', 'Mercedes', 'Tesla']

print('Total Elements: ', len(cars))  
  
# Output: Total Elements:  3

Iterating Through a List

We use a for loop to iterate over the elements of a list. For example,

fruits = ['apple', 'banana', 'orange']

# iterate through the list
for fruit in fruits:
    print(fruit)

Output

apple
banana
orange

Python List Methods

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

Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes item present at the given index
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
copy() Returns the shallow copy of the list

More on Python Lists

List Comprehension in Python

List Comprehension is a concise and elegant way to create a list. For example,

# create a list with square values
numbers = [n**2 for n in range(1, 6)]
print(numbers)    

# Output: [1, 4, 9, 16, 25]

To learn more, visit Python List Comprehension.

Check if an Item Exists in the Python List

We use the in keyword to check if an item exists in the list. For example,

fruits = ['apple', 'cherry', 'banana']

print('orange' in fruits)    # False
print('cherry' in fruits)    # True

Here,

  • orange is not present in fruits, so, 'orange' in fruits evaluates to False.
  • cherry is present in fruits, so, 'cherry' in fruits evaluates to True.

Also Read

Video: Python Lists and Tuples

Did you find this article helpful?