How to use Lists in Python

Lists are one of the fundamental object types in Python and also one of the most useful. Lists provide a flexible tool for storing arbitrary collections of data. Also unlike strings they are mutable.

>>> List = [123, 'Hello World!', 21.03, 'AAA']
>>> List
[123, 'Hello World!', 21.03, 'AAA']
>>> len(List)
4

We can use various methods to slice, index, concatenate just as we did for strings.

>>> List = [123, 'Hello World!', 21.03, 'AAA']
>>> List[0]
123
>>> List[3]
'AAA'
>>> List + ['New Element']
[123, 'Hello World!', 21.03, 'AAA', 'New Element']
>>> List
[123, 'Hello World!', 21.03, 'AAA']
>>> List * 3
[123, 'Hello World!', 21.03, 'AAA', 123, 'Hello World!', 21.03, 'AAA', 123, 'Hel
lo World!', 21.03, 'AAA']
>>> List
[123, 'Hello World!', 21.03, 'AAA']

Note that the original list remains unchanged even after manipulation. To create a new list using the old list you need to create a new object or use the append() method.

>>> new_list = List + ['New Element']
>>> new_list
[123, 'Hello World!', 21.03, 'AAA', 'New Element']
>>> List
[123, 'Hello World!', 21.03, 'AAA']

Lists can also nest other lists.

>>> another_list = [List, new_list]
>>> another_list
[[123, 'Hello World!', 21.03, 'AAA'], [123, 'Hello World!', 21.03, 'AAA', 'New E
lement']]

>>> len(another_list)
2

We can get to individual elements in the list using indexing.

>>> another_list[0]
[123, 'Hello World!', 21.03, 'AAA']
>>> another_list[1]
[123, 'Hello World!', 21.03, 'AAA', 'New Element']
>>> another_list[0][1]
'Hello World!'
>>> another_list[0][2]
21.03
>>> another_list[1][4]
'New Element'

You can modify a list using the append() or pop() methods.

>>> List
[123, 'Hello World!', 21.03, 'AAA']
>>> List.append('BBB')
>>> List
[123, 'Hello World!', 21.03, 'AAA', 'BBB']
>>> List.pop(0)
123
>>> List
['Hello World!', 21.03, 'AAA', 'BBB']

You can remove and insert objects into the list at arbitrary locations.

>>> List.insert(1, 'CCC')
>>> List
['Hello World!', 'CCC', 21.03, 'AAA', 'BBB']
>>> List.remove('CCC')
>>> List
['Hello World!', 21.03, 'AAA', 'BBB']

Leave a Reply

Your email address will not be published. Required fields are marked *