Lists
Lists in Python are equivalent to structures as dynamic vectors in programming languages such as C. We can express literals by enclosing their elements between a pair of brackets and separating them with commas. The first element of a list has index 0. The indexing operator allows access to an element and is expressed syntactically by adding its index in brackets to the list, list [index].
Consider the following example: a programmer can construct a list by appending items using the append() method, print the items, and then sort them before printing again. In the following example, we define a list of protocols and use the main methods of a Python list as append, index, and remove:
>>> protocolList = []
>>> protocolList.append("ftp")
>>> protocolList.append("ssh")
>>> protocolList.append("smtp")
>>> protocolList.append("http")
>>> print protocolList
['ftp','ssh','smtp','http']
>>> protocolList.sort()
>>> print protocolList
['ftp','http','smtp','ssh']
>>> type(protocolList)
<type 'list'>
>>> len(protocolList)
4
>>> position = protocolList.index("ssh")
>>> print "ssh position"+str(position)
ssh position 3
>>> protocolList.remove("ssh")
>>> print protocolList
['ftp','http','smtp']
>>> count = len(protocolList)
>>> print "Protocol elements "+str(count)
Protocol elements 3
To print out the whole protocol list, use the following code. This will loop through all the elements and print them:
>>> for protocol in protocolList:
>> print (protocol)
ftp
http
smtp
Lists also have methods, which help to manipulate the values inside them and allow us to store more than one variable inside it and provide a better method for sorting arrays of objects in Python. These are the most-used methods for manipulating lists:
- .append(value): Appends an element at the end of the list
- .count('x'): Gets the number of 'x' in the list
- .index('x'): Returns the index of 'x' in the list
- .insert('y','x'): Inserts 'x' at location 'y'
- .pop(): Returns the last element and also removes it from the list
- .remove('x'): Removes the first 'x' from the list
- .reverse(): Reverses the elements in the list
- .sort(): Sorts the list alphabetically in ascending order, or numerically in ascending order