Where Learning is Pleasure

Jayaram Krishnaswamy

Subscribe to Jayaram Krishnaswamy: eMailAlertsEmail Alerts
Get Jayaram Krishnaswamy: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Blog Feed Post

Accessing array items in Python is easy using indexing

Looks like a trick question.

There is no Array in Python but an object List exists which can be used to the same end.
  • The List may contain different list items or same kind of list items.
  • The List is indexed and zero based. The first list item has an index 0.
  • You can retrieve list items using their index. Even negative index is OK.
As defined here lst is a list .

lst=["a", "b", "c", "e"]

The list can have strings like this as well:

lst2=['a', 'b', 'c', 'e']

They both evaluate to the same: ['a', 'b', 'c', 'e']


List may contain different types of List Items as in this definition.


 lst2=["ab", 8, True, 5.8]

Retrieving list items using index
>>> lst[0]
'a'
>>> lst[-1]
'e'
>>> lst2[-2]
True
>>> lst[5]
Traceback (most recent call last):
  File "", line 1, in
IndexError: list index out of range

Negative Index
>>> lst[-1]
'e'
>>> lst2[-2]
True


These evaluations were carried out using Python 3.6.2



Read the original blog entry...

More Stories By Jayaram Krishnaswamy

Jayaram Krishnaswamy is a technical writer, mostly writing articles that are related to the web and databases. He is the author of SQL Server Integration Services published by Packt Publishers in the UK. His book, 'Learn SQL Server Reporting Services 2008' was also published by Packt Publishers Inc, Birmingham. 3. "Microsoft SQL Azure Enterprise Application Development" (Dec 2010) was published by Packt Publishing Inc. 4. "Microsoft Visual Studio LightSwitch Business Application Development [Paperback] "(2011) was published by Packt Publishing Inc. 5. "Learning SQL Server Reporting Services 2012 [Paperback]" (June 2013) was Published by Packt Publishing Inc. Visit his blogs at: http://hodentek.blogspot.com http://hodentekHelp.blogspot.com http://hodnetekMSSS.blogspot.com http://hodnetekMobile.blogspot.com He writes articles on several topics to many sites.