Lists in python

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 items from the list by passing its index inside [].

Example:

names = ['John', 'Jane', 'Jack', 'Jim']
print(names[0])
print(names[2])

Output:

John
Jack

If you pass the negative index then the list is accessed reversely.

Example:

names = ['John', 'Jane', 'Jack', 'Jim']
print(names[-1])

Output:

Jim

You can access a range of items by passing them in [] and setting the range between : symbol.

Example:

names = ['John', 'Jane', 'Jack', 'Jim']
print(names[1:3])

Output:

[‘Jane’, ‘Jack’]

You can access whole items from lists from the certain index like the 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 a certain item in the list, you can update it like following:

Example:

names = ['John', 'Jane', 'Jack', 'Jim']
names[0] = 'Jacky'
print(names)

Output:

[‘Jacky’, ‘Jane’, ‘Jack’, ‘Jim’]

Check out Recommended Posts:

Tuples in python

Dictionary in python

Functions in python

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments