Lists in Python

Introduction

A list is a data structure in python that is an ordered sequence of items. Each element in the list is referred to as an item. items are declared in double quotes and represented in between square brackets.

Lists are used to represent multiple items of similar type with a single name. Each element in the list also has its own identity.

Indexing Lists

Any element in an list can be accessed using the index of the list. Let us consider an list of 5 items, the index of the first element of the list will automatically be assigned as 0 and the last element of the list will be assigned the index 4. As you would have observed, the numbering of the indices of an list starts from 0 and ends at n-1 where n is the number of items in the list.

Examples

Index Errors: When we try to access an element that is beyond the range of the index we will receive an index error

Modifying Items in Lists

We can use indexing to modify the items within a list. We can modify/add the value of an element in a list by referring to the position of the element in the list.

Slicing Lists

We can also call out a small part of the list with a few items. This small  part of the list is called a slice.

Modifying Lists with Operators

We can use operators to modify the values of the items in a list.

We can use + operator to concatenate new items into the list. The * operator can be used to multiply the data collection and create multiple copies of items.

Removing an Item from a List

We can remove items from a list by using the del statement. This deletes the item in the mentioned index.

Constructing a List with List Items

Lists can also have other lists as items i.e. we can add a put a number of lists as items in a larger parent list.

Conclusion

The list data type is a flexible data type that can be modified throughout the course of your program.