English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, we will learn everything about Python lists; how to create them, how to slice them, how to add or delete elements from them, etc.
Python provides a series of compound data types that are usually called sequences. List is one of the most frequently used and widely used data types in Python.
In Python programming, a list is created by placing all items (elements) inside square brackets [] and separating them with commas.
It can have any number of items, and they can have different types (integers, floating-point numbers, strings, etc.).
# Empty list my_list = [] # Integer list my_list = [1, 2, 3] # List with mixed data types my_list = [1, "Hello", 3.4]
Similarly, a list can even have another list as an item. This is called a nested list.
# Nested list my_list = ["mouse", [8, 4, 6], ['a']]
We can access the elements of a list in many ways.
We can use the index operator [] to access items in a list. The index starts from 0. Therefore, it contains5of elements' list index ranges from 0 to4.
Attempt to access other elements; otherwise, an IndexError will be raised. The index must be an integer. We cannot use float or other types, which will cause a TypeError.
Use nested indexing to access nested lists.
my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2] # Output: e print(my_list[4] # Error! Only integers can be used for indexing # my_list[4].0] # Nested list n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1] # Output: 5 print(n_list[1]3]
Python allows negative indexing on sequences. The index-1represents the last item,-2represents the second-to-last item, and so on.
my_list = ['p','r','o','b','e'] # Output: e print(my_list[-1] # Output: p print(my_list[-5]
We can use the slicing operator (colon :) to access a series of items in a list.
my_list = ['p','r','o','g','r','a','m','i','z'] # From the3element to the5an element print(my_list[2:5] # From the start to the4an element print(my_list[:-5] # The6elements to the end print(my_list[5:]) # Elements from start to end print(my_list[:])
By considering the elements between the following indices, a slice can get the best visual effect. If we want to access a range, we need two indices to split that part from the list.
List is mutable, which means their elements can be changed without being likestringortuple.
We can use the assignment operator (=) to change a single item or a series of items.
# Value list odd = [2, 4, 6, 8] # Change the first element odd[0] = 1 # Output: [1, 4, 6, 8] print(odd) # Change the2to the4item odd[1:4] = [3, 5, 7] # Output: [1, 3, 5, 7] print(odd)
We can use the append() method to add an item to the list, or use the extend() method to add multiple items to the list.
odd = [1, 3, 5] odd.append(7) # Output: [1, 3, 5, 7] print(odd) odd.extend([9, 11, 13] # Output: [1, 3, 5, 7, 9, 11, 13] print(odd)
We can also use+Operator to combine two lists. This is also known as concatenation.
*Operator to repeat the list a given number of times.
odd = [1, 3, 5] # Output: [1, 3, 5, 9, 7, 5] print(odd + [9, 7, 5] # Output: ["re", "re", "re"] print(["re"] * 3)
In addition, we can use the insert() method to insert an item at a required position, or insert multiple items by compressing multiple items into an empty slice of the list.
odd = [1, 9] odd.insert(1,3) # Output: [1, 3, 9] print(odd) odd[2:2] = [5, 7] # Output: [1, 3, 5, 7, 9] print(odd)
We can use the keyword del to delete one or more items from the list. It can even completely delete the list.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # Delete one item del my_list[2] # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list) # Delete multiple items del my_list[1:5] # Output: ['p', 'm'] print(my_list) # Delete all list items del my_list # Error: List not defined print(my_list)
We can use the remove() method to delete a given item, or use the pop() method to delete an item at a given index.
If no index is provided, the pop() method will delete and return the last item. This helps us implement the list as a stack (a first-in-first-out data structure).
We can also use the clear() method to empty the list.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(','))1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list)
Finally, we can also remove items from the list by assigning an empty list to element slicing.
>>> my_list = ['p','r','o','b','l','e','m'] >>> my_list[2:3]= [] >>> my_list ['p', 'r', 'b', 'l', 'e', 'm'] >>> my_list[2:5]= [] >>> my_list ['p', 'r', 'm']
Below is a list of methods available for the list object in Python programming.
They are accessed in the form list.method(). Some methods have already been used.
Some examples of Python list methods:
my_list = [3, 8, 1, 6, 0, 8, 4] # Output: 1 print(my_list.index(8)) # Output: 2 print(my_list.count(8)) my_list.sort() # Output: [0, 1, 3, 4, 6, 8, 8] print(my_list) my_list.reverse() # Output: [8, 8, 6, 4, 3, 1, 0] print(my_list)
List comprehensions are a concise and clear way to create new lists from existing Python lists.
List comprehensions contain an expression followed by brackets insidefor statement.
This is a list that increments each item by2of the power example.
pow2 = [2 ** x for x in range(10) # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] print(pow2)
This code is equivalent to
pow2 = [] for x in range(10) : pow2.append(2 ** x)
List comprehensions can choose to include more for orif statementOptional if statements can filter out items from the new list. Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5] >>> pow2 [64, 128, 256, 512] >>> odd = [x for x in range(20) if x % 2 == 1] >>> odd [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> [x+y for x in ['Python', 'C'] for y in ['Language', 'Programming'] ['Python Language', 'Python Programming', 'C Language', 'C Programming']
We can use the keyword 'in' to test if an item exists in a list.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)
Using a for loop, we can iterate over each item in a list.
for fruit in ['apple', 'banana', 'mango']: print("I like", fruit)