Monday 17 June 2019

Lists in Python

Introduction

Lists in Python are analogous to arrays in Perl. A list holds a set of entities which could be strings or numbers. A list can in fact contain another list.
Declaring a list is fairly straight forward. Type the list name followed by the assignment operator (=) and then the list of items in square brackets separated by a comma.

>>> list=[1,2,3,4,'sahil']
>>> print list
[1, 2, 3, 4, 'sahil']
>>>

To access an individual element in the list type list_name[index]. Note that the indices start from 0 and not 1.

>>> print list[4]
sahil
>>>

Modifying lists:

There are a number of operations we can perform on lists to manipulate them. Here are a couple of examples.

Adding an element to a list:

>>> print list
[1, 2, 3, 4, 'sahil']
>>> list +=["hello"]
>>> print list
[1, 2, 3, 4, 'sahil', 'hello']
>>>


Substituting an element in the list:

>>> list=[1,2,3,4,'sahil']
>>> list[2]=9
>>> print list
[1, 2, 9, 4, 'sahil']


Replacing multiple items in a list:

>>> list[1:3]=[7,8]
>>> print list
[1, 7, 8, 4, 'sahil']
>>>
>>> list=[1, 7, 8, 4, 'sahil']
>>> list[1:2]=[2,3]
>>> print list
[1, 2, 3, 8, 4, 'sahil']
>>>


Removing multiple items in a list:

>>> list[1:3]=[]
>>> print list
[1, 4, 'sahil']
>>>


Add an element using append function:

>>> list.append('world')
>>> print list
[1, 2, 3, 8, 4, 'sahil', 'world']
>>>


Remove list element using pop function:

>>> list.pop(2)
3
>>> print list
[1, 2, 8, 4, 'sahil', 'world']
>>>


Remove list element using it's value:

>>> list.remove('sahil')
>>> print list
[1, 2, 8, 4, 'world']
>>>


Conclusion

This concludes our discussion on lists in Python. We hope that you found this quick and simple explanation to be useful.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...