Python List is a compound data type that can be used to store values that may or may not be similar. Python list is not an array since array needs to have items of same data type. If you have experience of programming in language like C you will understand the difference. Those who are new to Python can understand it this way. A python list is like a bag where you can fill up anything that you like. But an array is like a bag where you can fill up only one kind of things.
Recall Python Data Types topic discussed already. There are a few basic data types like number, string and complex. Python list is a collection of different items that may belong to these basic data types.
Syntax of a Python List
A python list is always declared as a variable name and the set of values of different data types that make a list is enclosed in a square bracket .
Here List-name is the name of the list that you want to create. Value1, Value2.. are the items of the list separated by commas. If an item of a list is a string it must be written in single quotes. A numeric value must be written without single quotes. A number written in single quotes is also a string.
my_address=[42, ‘West’,’Madison St’,’Chicago’, ‘IL’,'(773) 523-1021′, 60602]
List items can also be identified, referred or accessed by the indices just like individual characters of a string variable. For that you need to write the name of the list and the required index with in square brackets. The indices of the elements start with 0 and last index is 1 less than the total count of list elements.
In the list declared in this example we have 7 elements. Fist element is a 0th index and last element is at 6th index. A negative index value in square parenthesis returns the elements from the end.
In the example below you can see that by writing the name of the list, you get all the elements of list my_address.
When you give index 2 in square parenthesis, you get element at third location in list.
If you give index 0 in parenthesis you get the first element of the list.
With index 6 you get the last element displayed.
With index -2 you get 2nd element from end of the list