In Python, list and tuple are sequences. The difference between list and tuple is that the list can be changed while tuple can’t be changed. You can insert, update, or delete items of the list but you can’t do that with the tuple.
Lists: creating a list
Let’s create a list to store the names of months of the year.
>>> months=['January', 'February','March','April','May','June','Junly','August','September','October','November',
['January', 'February', 'March', 'April', 'May', 'June', 'Junly', 'August', 'September', 'October', 'November', 'December']
Lists: Accessing list elements
You can access a list element by specifying its number. The numbers of the list ranks from 0 upwards.
You can access the list elements from the last to the beginning by using negative number:
You also can access a range of the list elements by using a range of numbers:
['January', 'February', 'March', 'April', 'May', 'June']
['Junly', 'August', 'September', 'October', 'November']
If you want to access the elements from a position to the end, you can specify the start number and leave the end black:
['June', 'Junly', 'August', 'September', 'October', 'November', 'December']
['October', 'November', 'December']
Note: A string is also a sequence. Therefore, to access characters in a string you need to specify their numbers.
In accessing the list elements you can specify the step:
List: adding lists
In Python, you can not only add numbers but also you can add sequences.
[1, 2, 3, 4, 5, 6]
List: multiplying lists
You can multiply a sequence with a number.
[1, 2, 3, 1, 2, 3]
List: checking membership
You can use in operator to check whether a value is in a sequence.
>>> 1 in lst4
>>> 'H' in 'Hello'
List: lists in list
An element of a list can be a list.
List: len, min, and max
len() method is used to get the number of items in a list while min() and max() are used to get the minimum, and the maximum elements of the list.
List: changing list elements
[1, 2, 5]
[12, 15, 5]
List: deleting list elements
You can delete list elements by using del keyword.
>>> del lst1
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: