A list in Python is a compound data type for storing a sequence of values or elements. A list is created by placing its elements in a square bracket ([]) separated by commas. Example
# A list of strings
sample_list = ["Apple", "Mango", "Orange"]
A list can contain elements of different data types
# A list of mixed data types
mixed_list = ["Apple", 10, 3.6]
A list may also be empty
# An empty list
empty_list = []
The individual elements of a list can accessed by zero-based indexing. The first element in a list has an index 0, the next has an index 1 and so on. Examples:
sample_list = ["Apple", "Mango", 12, 10.5]
print(sample_list[0])
print(sample_list[2])
Outputs:
Apple
12
Negative integers starting from -1 can be used to access elements in a list from the end.
sample_list = ["Apple", "Mango", 12, 10.5]
print(sample_list[-1])
Output:
10.5
sample_list = ["Apple", "Mango", 12, 10.5]
print(sample_list[-3])
Output:
Mango
Lists in Python are not immutable. New elements can be added to and existing elements can be removed from lists. Also elements in lists may be replaced. To add a new element to a list, use the 'append' function on the list.
sample_list = ["Apple", "Mango", 12, 10.5]
sample_list.append("Orange")
print(sample_list)
Output:
['Apple', 'Mango', 12, 10.5, 'Orange']
To replace the element 12 with 17:
sample_list = ["Apple", "Mango", 12, 10.5]
sample_list[2] = 17
print(sample_list)
Output:
['Apple', 'Mango', 17, 10.5]
To delete an element from a list:
sample_list = ["Apple", "Mango", 12, 10.5]
del sample_list[1]
print(sample_list)
Output:
['Apple', 17, 10.5]