Lists in python are one of the ways to store data.
- Lists in python store values in a sequence. The values can be of any data type.
- You can make a list of lists.
- Lists in python have many in-built functions that make things like sorting, reversal and finding max and min values trivial.
- Lists are mutable i.e. any one of the items of the last can be changed to have another value.
- Elements can be added or removed from a list.
Declaring an empty list
To make an empty list, write:
lst = []
The square bracket notation is used to denote a list.
lst = ["val1","val2","val3","val1","val3"]
Appending a value
To add a new value to the list, write:
lst.append("val1")
Removing a value
To remove an element from the list, write:
lst.remove("val4")
Remember: This will only remove the first occurrence of the passed value.
Sorting a list
To sort a list, simply call its sort method.
lst = [1,0.1,2,4,3]
lst.sort()
Reversing a list
To reverse the elements in a list, use the reverse method of the list.
ls = [1,3,5,7,9]
ls.reverse()
Note: You can use the sort method and then the reverse method to get the list in decreasing order. Alternatively, you can use lst.sort(reverse=True) to do the same.