What is list in Python?
Python Lists are an ordered collection of items within square brackets []
.
How to create a list in Python
We use the square brackets ([])
to create a list. We can create an empty list.
An_empty_list = []
The following example shows how you can create a list of some actual items in Python.
cars=["Tesla", "Ford", "Toyota"]
print(cars)
['Tesla', 'Ford', 'Toyota']
How to create a list using list()
You can also use the list()
double round brackets to create a list.
car_list = list(("Tesla", "Ford", "Toyota"))
print(car_list)
['Tesla', 'Ford', 'Toyota']
How to check length of a list
We can also check the length of a list by using the len()
function. The following example shows how you can check the number of elements in a Python list.
cars=["Tesla", "Ford", "Toyota"]
print(len(cars))
3
How to check data type for a list
We can check whether an object is a list using type()
function in Python. The following is the Python code example.
print(type(cars))
<class 'list'>
How to Index List in Python
You can also select elements within a list by using square brackets[]
and index numbers
. The following is the example showing that.
print(car_list[0])
Tesla
How to sum, min, or max lists in Python
You can calculate the sum, smallest element, and largest element of a list using sum()
, min()
, and max()
.
list_numbers= [1,2,3, 4,6,4,7,8]
print(sum(list_numbers))
print(min(list_numbers))
print(max(list_numbers))
35 1 8
How to modify, append, and insert elements in Python Lists
We can then replace the first element of the list using square brackets[0]
with the number 20.
list_numbers= [1,2,3,4,6,4,7,8]
list_numbers[0]=20
print(list_numbers)
[20, 2, 3, 4, 6, 4, 7, 8]
We can add elements into a list using append()
or insert()
in Python.
numbers_append= [1,2,3,4,6,4,7,8]
numbers_append.append(50)
print(numbers_append)
numbers_insert= [1,2,3,4,6,4,7,8]
numbers_insert.insert(5,50)
print(numbers_insert)
After running the code above, the following is the output showing the result after adding the element.
[1, 2, 3, 4, 6, 4, 7, 8, 50] [1, 2, 3, 4, 6, 50, 4, 7, 8]
How to delete or remove elements in Python Lists
The following code shows how you can delete an element in a list by using the del statement.
list_numbers= [1,2,3,4,6,4,7,8]
print(list_numbers)
del list_numbers[1]
print(list_numbers)
[1, 2, 3, 4, 6, 4, 7, 8] [1, 3, 4, 6, 4, 7, 8]
You can also use the remove element by using the remove statement.
list_numbers= [10,90,30,40,60,40,70,80]
print(list_numbers)
list_numbers.remove(90)
print(list_numbers)
After running the code above, the following is the output.
[10, 90, 30, 40, 60, 40, 70, 80] [10, 30, 40, 60, 40, 70, 80]
How to combine lists in Python
You can use the + operator
to merge two or more lists into a new list. For example:
Black= [5,1,2,5,4]
Blue=[7,3,7,5,10]
Yellow=[3,3,1,1,2]
print(Black+Blue+Yellow)
[5, 1, 2, 5, 4, 7, 3, 7, 5, 10, 3, 3, 1, 1, 2]