Wednesday, October 28, 2015

Python Tutorial: Indexing Python List - Python List #84



To learn more about list in Python visit our website at http://learnpythontutorial.com/indexing-list-in-python/

Indexing List In Python

In this Python tutorial, we will teach you all about indexing list in Python. Indexing list in Python is a very important concept which gives us the ability to access our objects that appear in a list. List in Python can contain a lot of information that is important in order to run our programs and having a way to access the content within a list allows us to use the content as it is needed when our program runs. Indexing allows us to access one object and slicing allows us to access numerous objects at one time.



Indexing List In Python Explained

[table id=9 /]



In the above table, you can see the indexing of a list is very similar to indexing strings. The only difference is that in the list each object holds an index position where in strings each character holds an index position. As always the index always starts at 0 and counts up for each object contained in a list. If we want to access an object going from the end of a list(right to left), we use a negative index number. The last index position when going right to left always starts at -1.



Examples Of Indexing List in Python

Access Index From Left To Right



 a = ['List', 12345, [123, 456]]

 a[1]

12345

a = ['List', 12345, [123, 456]] - We create a list object that contains a string object, number object and another list object. We assign our list object a variable named 'a' to represent the list.



a[1] - We call our list object via the variable 'a' then we request the index position of 1.



12345 - We are returned the 1 index positions object which happens to 12345.



Access Index From Right To Left



 a = ['List', 12345, [123, 456]]

 a[-1]

[123, 456]

a = ['List', 12345, [123, 456]] - We create a list object and assign the list a variable of 'a'.



a[-1] - We then call our list via the variable of 'a' and we then index from the right using a negative index position. Remember when indexing from the right we need to use negative numbers and the starting index position from the right is -1.



[123, 456] - We are returned a list that was contained in our list object. The list object is the last object contained in the list and we used -1 to access this list object.



Conclusion



In this Python tutorial, we looked at accessing list using indexing which is vital in programming when using list. If we can not access our content stored in list then list would be useless. We can pull one object out of a list using indexing if we need to pull more we could index multiple times or we can use slicing which we will cover in the next tutorial. If you have any questions about indexing in Python leave a comment below.



In this tutorial we use Python 3.5.0

No comments:

Post a Comment