Lists in python are used to store a collection of values.
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
print(names)
Output:
[‘John’, ‘Jane’, ‘Jack’, ‘Jim’]
Accessing the lists:
You can access item from list by passing its index inside [].
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
print(names[0])
print(names[2])
Output:
John
Jack
If you pass negative index then list is accessed reversely.
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
print(names[-1])
Output:
Jim
You can access range of items by passing them in [] and setting range between : symbol.
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
print(names[1:3])
Output:
[‘Jane’, ‘Jack’]
You can access whole items from lists from certain index like following:
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
print(names[1:])
Output:
[‘Jane’, ‘Jack’, ‘Jim’]
Modifying lists:
Lists in python can be modified. If you want to update certain item in list, you can update it like following:
Example:
names = ['John', 'Jane', 'Jack', 'Jim']
names[0] = 'Jacky'
print(names)
Output:
[‘Jacky’, ‘Jane’, ‘Jack’, ‘Jim’]