Lists in Python with example

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ( [ ] ). To some extent, lists are similar to arrays in C. One difference between List is that all the items belonging to a list in Python can be of different data type. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. Let's suppose we have the following list in our Python shell:

>>> days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

Here is how to access the first three items (from first to third):

>>> days[0:3]

Output of the above is as following:

['Mon', 'Tue', 'Wed']

Now lets Access items from first to fourth:

>>> days[0:4] 

O/P : ['Mon', 'Tue', 'Wed', 'Thu'] 

The following syntax is also same as above:

>>> days[:4] 
O/P : ['Mon', 'Tue', 'Wed', 'Thu'] 

Print a List with No boundaries, or all the elements of the List:

>>> print  days[:] 
O/P : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] 

Print From first to second-to-last element:

>>> print  days[0:-1] 
O/P : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] 

Print From first to third-to-last:

>>> print days[:-2] 
O/P : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] 

From third-to-last to second-to-last:

>>> days[-3:-1] 
O/P : ['Fri', 'Sat'] 

From third-to-last to last :

>>> days[-3:] 
O/P : ['Fri', 'Sat', 'Sun']

Following are some consolidated example of List:

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

 

Python 12

FOLLOW US ON LinkedIn



Explore Tutu'rself