Lists in Python.


Lists:

A list is an ordered sequence of values. It is of non-scaler type. Values stored in a list can be of any type such as string, integer, float or list. Data structures are containers that organize and group data types together in different ways. A list is one of the most common and basic data structures in Python.

You saw here that you can create a list with square brackets. 

For example: A list is used to store the name of the subjects.

>>>subjects=["Math","English","Hindi"]

Lists can contain any mix and match of the data types you have seen so far.

>>>list_of_random_types =  [1, 3.4, 'a string', True]
 


Indexing of List:

This is a list of 4 elements. All ordered containers (like lists) are indexed in python using a 
starting index of 0. Therefore, to pull the first value from the above list, we can write:

>>> list_of_random_types[0]

1

It might seem like you can pull the last element with the following code, but this actually won't work:

>>> list_of_random_types[len(list_of_random_things)] 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-34-f88b03e5c60e> in <module>()
----> 1 lst[len(lst)]

IndexError: list index out of range





However, you can retrieve the last element by reducing the index by 1. Therefore, you can do the following:

>>> list_of_random_types[len(list_of_random_types) - 1] 

True

Alternatively, you can index from the end of a list by using negative values, where -1 is the last element, -2 is the second to last element and so on.


>>> list_of_random_types[-1] 
True
>>> list_of_random_types[-2] 
a string 


Post a Comment

0 Comments