Wednesday, January 17, 2018

Lists in Python



Python Lists

  • The list is the most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between square brackets. 
  • The items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];


Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])




When the above code is executed, it produces the following result −
list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]


Snapshot of some examples:

Nested List  : These are list within a list


No comments:

Post a Comment