A list a data container which keeps values (numbers, strings, objects). The values should have the same type, which can be checked with the command type(value). Values in a list are numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. Let us make a list of numbers:
The list can be written as a list of comma-separated values (items) between square brackets.
In fact, one can first specify an empty list and then add the numbers using the append method.
We can calculate the length of this list using the function len(). Also you can access any element of the list using it's index:
Often we need to create a large lists, in which case typing a long list become tedious. In this case use the statement range() It takes at least 2 parameters: first the number at which the list it returns should start, and second, the number up to which the list should go.
range() takes an optimal third parameter that specifies the step between each number in the list:
The for-in statement makes it easy to loop over the items in a list:
If you need both the index and the item, use the enumerate function:
If you need only the index, use range and len:
Python provides various shortcuts for common list operations. For example, if a list contains numbers, the built-in sum function gives you the sum:
If a list contains strings, you can combine the string into a single long string using the join string method:
Python also provides built-in operations to search for items, and to sort the list.
The list type also allows you to assign to individual items or slices, and to delete them.
To create a separate list, you can use slicing or the list function to quickly create a copy:
The append method adds a single item to the end of the list, the extend method adds items from another list (or any sequence) to the end, and insert inserts an item at a given index, and move the remaining items to the right.
To insert items from another list or sequence at some other location, use slicing syntax:
You can also remove items. The del statement can be used to remove an individual item, or to remove all items identified by a slice. The pop method removes an individual item and returns it, while remove searches for an item, and removes the first matching item from the list.
The list type allows you to quickly reverse the order of the list, L.reverse()