List In Python & How To Manipulate Them

Lists are exactly what they sound like. They are a list of objects - each object is called an element, and each element is of the same or different data type. Note that there is no requirement to have all elements in a list be of the same data type.

you can make list of your router hostname
>>> hostname=['R1', 'R2', 'R3', 'R4', 'R5', 'R6']
>>> print hostname
['R1', 'R2', 'R3', 'R4', 'R5', 'R6']
>>> hostname
['R1', 'R2', 'R3', 'R4', 'R5', 'R6']

In some case you can create an array which is contain a list of command or any data. In this example I make list of command to enable an interface.

>>> commands=['config t', 'interface gi1/1', 'no shutdown']
>>> commands
['config t', 'interface gi1/1', 'no shutdown']

Index
You can also print each element one by one like this
>>> print commands[0]
config t
>>> print commands[2]
no shutdown

Append()
You can add element into the variable of list
>>> commands.append('exit')
>>> print commands
['config t', 'interface gi1/1', 'no shutdown', 'exit']
The element automatically saved in the last index

Insert()
Rather than just append an element to a list, you may need to insert an element at a specific location.
>>> print commands
['config t', 'interface gi1/1', 'no shutdown', 'exit']
>>> commands.insert(0, 'enable')
>>> print commands
['enable', 'config t', 'interface gi1/1', 'no shutdown', 'exit']
See that the 'enable' added to the index 0 (the first index)

Join()
you can put a characters to separate them.
>>> print ' ; '.join(commands)
config t ; interface gi1/1 ; no shutdown

also you can make EOL (end of line) betwen each command
>>> print ' \n '.join(commands)
config t
 interface gi1/1
 no shutdown

Pop()
You can remove the elemen on a list using pop()
>>> print host
['r1', 'r2', 'r3']
>>>
>>> host.pop()
'r3'
>>> print host
['r1', 'r2']
>>> host.pop(0)
'r1'
>>>
>>> print host
['r2']


Tulis komentar anda... Conversion Conversion Emoticon Emoticon

Thanks for your comment