A list is a value that contains multiple values in an ordered sequence. Lists are mutable in so far as the elements within them can be replaced or removed, and new elements can be inserted or appended. Lists are delimited by square brackets, and the items within the list separated by commas.
Elements are zero based index
List | P | Y | T | H | O | N |
---|---|---|---|---|---|---|
Index | 0 | 1 | 2 | 3 | 4 | 5 |
Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
List with string elements
Integer List
String list
>>> ["apple","orange","banana"] # String list
['apple', 'orange', 'banana']
List can have elements with multiple data types
List can have sub list with in them
Note: [1,10] and [2,11] are sub list
list() function can be used to create a list
>>> l=list()
>>> l.append(1)
>>> l.append(2)
>>> l
[1, 2]
>>> l.append([3,4]) # Notice element is added as list object not int
>>> l
[1, 2, [3, 4]]
>>> l.extend([5,6])# each element got added as a separate element towards the end of the list.
>>> l
[1, 2, [3, 4], 5, 6]
>>> l.insert(0,0) # Insert element at particular index
>>> l
[0, 1, 2, [3, 4], 5, 6]
>>> list("Welcome to Python")
['W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
Elements in the list can be retrieved by using Index
>>> l=["P","Y","T","H","O","N"]
>>> l[0] # Get first element
'P'
>>> l[5] # Get last element
'N'
>>> l[-1] # Get last element with index as -1
'N'
>>> l[-6] # Get first element using negative index
'P'
Get sub list from a given list . General Syntax
Note: endIndex element will not be retrieved
>>> l=["P","Y","T","H","O","N"]
>>> l[0:1] # Get element from index 0 till index 1. Note element with endIndex is ignored
['P']
>>> l[:] # Get all the elements
['P', 'Y', 'T', 'H', 'O', 'N']
>>> l[1:] # Get elements from index 1 to till end
['Y', 'T', 'H', 'O', 'N']
>>> l[:6] # Get elements from starting to index 6
['P', 'Y', 'T', 'H', 'O', 'N']
Most commonly used methods on the lists
Appends elements to the list
Removes element from the list
Remove element at specific index