Python Programming – List

In this Page, We are Providing Python Programming – List. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – List

List

Python has a number of built-in types to group together data items. The most versatile is the list, which is a group of comma-separated values (items) between square brackets. List items need not be of the same data type.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a
[ ' spam ' , ' eggs ' , 100 , 1234 ]

Python allows adding a trailing comma after the last item of list, tuple, and dictionary, There are several reasons to allow this:

  • When the list, tuple, or dictionary elements spread across multiple lines, one needs to remember to add a comma to the previous line. Accidentally omitting the comma can lead to errors that might be hard to diagnose. Always adding the comma avoids this source of error (the example is given below).
  • If the comma is placed in each line, it can be reordered without creating a syntax error.

The following example shows the consequence of missing a comma while creating a list.

>>> a=[
         ' hi ' , 
         ’ hello ’ 
         ' bye ’ , 
         ' tata ' , 
         ] 
>>> a
[ ' hi ' ,  ' hellobye ' ,  ' tata ' ]

This list looks like it has four elements, but it actually contains three: ‘ hi ‘,  ‘ hellobye ‘, and  ‘ tata ‘. Always adding the comma avoids this source of error.