29th, January, 2020
To declare a list you will need to use square brackets.
mylist = []
A list can contain numbers or mixes of data types together within the brackets. Each item in a list is called an element. Each of these elements will have an index number. The index numbering as with strings begins at 0. Same with strings lists can be indexed using negative numbers. Two index numbers can also produces ranges.
mylist = [1, 2, 3, 4, 5]
print (mylist[0])
print (mylist[1:3])
print (mylist[-1])
>>>
1
2, 3
5
You can replace items inside of lists by reassinging indexed values to equal new ones.
mylist = [1, 2, 3, 4, 5]
mylist[0] = [6]
mylist[1:3] = [8, 10]
mylist[-1] = [14]
print (mylist)
>>>
[6, 8, 10, 4, 14]
Similarly you can remove items from the list using the same process however equalling it to empty square brackets. To clear a list do [:] = []
It is also possible to nest lists inside of other lists.
mylist = [1, 2, 3]
mylistnew = [mylist, 4, 5]
print (mylistnew)
print (mylistnew[0])
print (mylistnew[0][2])
>>>
[[1, 2, 3], 4, 5]
[1, 2, 3]
3
Lists also allow for counting of the objects inside of them using the len() operation. This is the same that is used for strings.
To add items to the end of a list it is recommended to use .append()
You can also extend a list using another list by using .extend()
It is also possible to insert an item into a list at a given position. To do this you must use .insert(index, x)
You can also remove items from the list that have the value of that is equivalent of x using .remove(x)
You can remove an item at a given position and return it using .pop()
You can also find the index of an item in the list by replacing x with what you're searching for in .index(x)
You can return the number of items that something appears by replacing x in .count(x)
It is also possible to sort the contents of a list using .sort()
Lastly you can reverse the elements of the list in place using .reverse()
mylist = ["Code", "Easy", "Hello", "World"]
index = 0
while index < len(mylist):
print (mylist[index])
index = index + 1
>>>
Code
Easy
Hello
World
>>>
mylist = ["Code", "Easy", "Hello", "World"]
for word in mylist:
print (word)
>>>
Code
Easy
Hello
World