Dealing Arrays in programming is very important. Lists are very similar to Array concept in programming language. A list can contain any types of variables. This can include variables like, integer, string etc, whatever you wish to add as a List.
Python is a good and simple language for SysAdmins automation tasks. Go to the Index page and read more about Python.
In this article we are discussing about Lists and Sequences in Python language. This is simply a function to store data as a list.
List_name = ['entry1',"entry2','entry3',.....,'entryn']
First part “List_name” is the List’s name. You need this name to access data from the List. Next is an equal sign, then add or enter data into the square bracket.
Please see an example List with string variables:
MyFam = ['Dad','Mom','Wife','Sis','Bro']
After hitting the enter button, the data in the square bracket will store as a List in the system (server), somewhere, that doesn’t matter 😛
In the above example, we entered five strings to the List “MyFam.” Each entry has a specific index number, which starts from 0 to n. In this example, the index number of string “Dad” is 0 and “Bro” is 4. This is very important as this is required to access each individual elements from the Array (List).
Accessing elements from an Array/List
As I mentioned earlier, you must know the index number to access an element or elements from a List. The examples added below will explain it:
MyFam = ['Dad','Mom','Wife','Sis','Bro'] MyFam Out: 'Wife' MyFam Out: 'Bro' MyFam IndexError: list index out of range print MyFam Wife print MyFam + " and " + MyFam Bro and Sis
Appending elements into Arrays
Here I am going to append one more element to the Array “MyFam.”
c = "Me" MyFam.append(c) print MyFam Me
How to list all elements in an Array/List?
You can simply use a for loot to list all elements in a Python list. Please see the example added below:
>>> : for x in MyFam: ....: print(x) ....: Dad Mom Wife Sis Bro Me
Reverse access; accessing elements from last.
Accessing backward is also important in List. The backward index of last element is -1. In our above example (MyFam = [‘Dad’,’Mom’,’Wife’,’Sis’,’Bro’]) the element “Bro” has backward index -1 and index of “Sis” is -2 and so on.
MyFam = ['Dad','Mom','Wife','Sis','Bro'] MyFam[-2] : 'Sis' print MyFam[-2] Sis
FYI, as List (Array) string in Python also has index number. Please see the example: a = "This is Python" print a s print a[-3] h
Okay. Let’s play with arrays and let me know if you have any questions.
Also read Variables and Types – Python