Python Lists
What are Lists?
Lists are ordered collections of elements. The elements can have any data type and you can mix data types. You can set, create, and remove elements.
Making Lists
To make lists, we seperate our elements with commas and wrap the entire thing in square brackets ([
and ]
), which tells Python that we're making a list. We can put whatever we want in there. For example:
my_list = ["Learnmonkey", 25, 8.452, False]
Accessing List Elements
To access a list element, we type:
list[index]
list
is the name of the list variable and index
is the index of the element. Indexes start at zero for the first element and go up by one for each element. For example, the element with array index 2 is the third element and the element with array element 4 is the fifth element.
For example:
my_list = ["Learnmonkey", 25, 8.452, False]
print(my_list[0])
print(my_list[2])
print(my_list[3])
The above code returns:
Learnmonkey 8.542 False
Setting List Elements
To set a list element, we type:
list[index] = value
list
is the name of the list variable, index
is the index of the element, and value
is the value you want to set the element. For example:
my_list = ["Learnmonkey", 25, 8.452, False]
my_list[0] = "Stack Overflow"
my_list[2] = 3.141
print(my_list)
.
The above code returns:
['Stack Overflow', 25, 3.141, False]