What is a List in Python
A list in Python is a data structure that represents a modifiable, or alterable, ordered series of elements.
The list is one of four built-in data types in Python that are used to store collections of data; the other three are Tuple, Set, and Dictionary, each of which has distinct characteristics and uses.
Python lists are one of the most useful types of data because they let us work with multiple elements at once. A list can include any number of items and their types can vary (integer, float, string, etc.).
Example:
list1 = ['Prince', 'Grace', 1999, 1998];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["A1", "B2", "C3", "D4"]
The list is a type of data that is mutable. Once a list has been made, elements can be changed, individual values can be changed, and the order of elements can be changed.
A pair of empty square brackets [] or the type constructor list() can be used to create an empty list.
Creating a list in Python is as easy as placing values separated by commas between square brackets.
Accessing Lists in Python Values
Accessing lists in Python values lets you combine the square brackets for slicing with the index or indices to obtain the value accessible at that index.
Example:
list1 = ['Prince', 'Grace', 1999, 1998];
list2 = [1, 2, 3, 4, 5 ];
print (list1[3])
print (list2[1:4])
Output:
1998 [2, 3, 4]
Updating Lists in Python
Updating Lists in Python allows you to update or modify single or multiple list items by placing the slice to the left of the assignment operator.
Example:
list1 = ['Prince', 'Grace', 1999, 1998];
print ("The current value of list[2] is", list1[2])
list1[2] = 2022
print ("The new value of list[2] is", list1[2])
Output:
The current value of list[2] is 1999 The new value of list[2] is 2022
Delete List Elements
To delete list elements, you can use the del statement; otherwise, you can use the remove() method if you know precisely which element(s) you wish to delete.
Example:
list1 = ['Prince', 'Grace', 1999, 1998];
print (list1)
del list1[0];
print ("The list after deleting the index 0:")
print (list1)
Output:
['Prince', 'Grace', 1999, 1998] The list after deleting the index 0: ['Grace', 1999, 1998]
The remove() is discussed in the List Functions and Methods.
Basic List Operators
The Basic List Operators such as + and * operators behave similarly on lists as they do on strings; they represent concatenation and repetition, but the result is a new list, not a string.
In fact, lists respond to every general sequence operation we used on strings in the previous chapter.
Example:
print(len(['a', 'b', 'c']))
print([1, 2, 3] + [4, 5, 6])
print(['Hey!'] * 4)
print(3 in [1, 2, 3])
for x in [1, 2, 3]: print (x)
Output:
3 [1, 2, 3, 4, 5, 6] ['Hey!', 'Hey!', 'Hey!', 'Hey!'] True 1 2 3
Indexing, Slicing, and Matrixes
Lists in Python are sequences, so the indexing, slicing operator, and matrixes work identically for both lists and strings.
Considering the following input:
Example:
list1 = ['code', 'Code', 'CODE!']
print( list1[2] )
print( list1[-2] )
print( list1[1:] )
Output:
CODE! Code ['Code', 'CODE!']
Python is different from other languages because it lets you use negative indexing.
From the right, you can count the negative indices. Below is an illustration of how the slicing works in List.
List Functions & Methods
Here is the list of Built-in List Functions and Methods in Python.
List Functions
The following list functions are supported by Python:
Function | Description |
---|---|
cmp(list1, list2) | Elements from both lists are compared. |
len(list) | This function returns the overall length of the list. |
max(list) | Returns the item from the list with the maximum value. |
min(list) | Returns the item from the list with the minimum value. |
list(seq) | A tuple is converted into a list. |
Example:
list1 = ['Prince', 'Grace', 'Mario', 'Ludy', 'Mc Quinn']
# cmp is not support in Python 3 but it is still workiin in Python 2
# len
print (len(list1))
# max
print (max(list1))
# min
print (min(list1))
tuple1 = ('Prince', 'Grace', 'Mario', 'Ludy', 'Mc Quinn')
# list
print (list(tuple1))
Output:
5 Prince Grace ['Prince', 'Grace', 'Mario', 'Ludy', 'Mc Quinn']
Note that cmp() is not supported in Python 3.
Python List Methods
The following list methods are supported by Python:
Methods | Description |
---|---|
list.append(obj) | Append method Adds the object obj to the list |
list.count(obj) | Returns the number of times obj appears in the list. |
list.extend(seq) | The contents of seq are added to the list. |
list.index(obj) | The lowest index in the list at which obj occurs. |
list.insert(index, obj) | Inserts object obj at offset index into list |
list.pop(obj=list[-1]) | Removes and returns the final object or obj from the list and returns it. |
list.remove(obj) | Removes the object obj from the list. |
list.reverse() | Objects in the list are reversed in place. |
list.sort([func]) | Objects in the list are reversed in place. |
Example:
list1 = ['Prince', 'Grace', "1990", "2000", "2022"]
# append
list1.append("1999")
print(list1)
# count
print(list1.count("2000"))
# extend
list2 = ['banana', 'apple', 'orange']
list1.extend(list2)
print(list1)
# index
print(list1.index("2000"))
# insert
list1.insert(1, "5000")
print(list1)
# pop
print(list1.pop())
# remove
list1.remove("2000")
print(list1)
# reverse
list1.reverse()
print(list1)
# sort
list1.sort()
print(list1)
Output:
['Prince', 'Grace', '1990', '2000', '2022', '1999'] 1 ['Prince', 'Grace', '1990', '2000', '2022', '1999', 'banana', 'apple', 'orange'] 3 ['Prince', '5000', 'Grace', '1990', '2000', '2022', '1999', 'banana', 'apple', 'orange'] orange ['Prince', '5000', 'Grace', '1990', '2022', '1999', 'banana', 'apple'] ['apple', 'banana', '1999', '2022', '1990', 'Grace', '5000', 'Prince'] ['1990', '1999', '2022', '5000', 'Grace', 'Prince', 'apple', 'banana']
What is list comprehension in Python?
List comprehension is a simple and elegant way to make a new list out of an existing list in Python.
An expression followed by a for statement enclosed in square brackets constitutes a list comprehension.
Example:
sample = [2 ** i for i in range(5)]
print(sample)
Output:
[1, 2, 4, 8, 16]
This code corresponds to:
sample = []
for i in range(5):
sample.append(2 ** i)
Summary
You’ve learned Python list functions and methods with examples. This lesson addressed accessing values, updating and removing lists, fundamental operations, indexing, slicing, and matrices.
I hope that you’ve learned how to use Python strings from this lesson. If you missed any of our prior lectures, check out our collection of Python Tutorial Topics.
The following post, “Python Tuples,” will instruct you on how to use the built-in functions.
Python Strings
Python Tuples