Lists in Python

Lists in Python – is a sequence data type. In a sequence, each element is assigned a sequence number or, an index. The index numbers start with zero. So, first index is assigned zero, second index is assigned one and so on till the end of the sequence.

Up-till now, a variable can store a single element. But, with the help of lists we can store multiple of those in a single variable. Apart from that, if needed we can also make changes to the list. But, any new additions to the list would happen at the end.

Also, square brackets [ ] are used to create lists and commas separate items of the list.

Now, understand it with help of an example –

listex=['book', 'science', 9]

To check whether the above is a list or not –

print(type(listex))

It would return with –

<class 'list'>

Next, we turn to couple of operations which we can do on lists. First, we will start with finding the length of our list. So, to find the number of items in our list – we use len() function. Continuing with above example –

print(len(listex))

It would return with –

3

To get a particular item from the list using index number. Let’s say we want to get the item at index number 1 in the above example –

listex[1]

This would show –

'science'

Thirdly, to append an item at the end of the list –

listex.append('not available')

To view the changes to the list –

print(listex)

It shows the output –

['book', 'science', 9, 'not available']

One more thing we would like to add here before concluding. We can have duplicate items in the list. In that case, the index number of duplicate items would be different. Take following list containing duplicate items –

listdup=['book', 'science', 'book']

And, do –

print(listdup)

It would return with –

['book', 'science', 'book']

In conclusion, we have introduced you to the lists in this article. We will see various operations which we can perform on list in subsequent articles. Also, we will discuss tuples after we finish lists. So, interesting days ahead!

Similar Posts