Glen Knight

NYC Based IT Professional

Python List Basics

Lists
Lists are a data structure in Python that is mutable and each element of a list is referred to as an item, and are defined as comma delimited values between square brackets [ ].

Example:

sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', ‘anemone']

Lists can be compared to ArrayLists in other programming languages, and are referred to by their indices, which start at 0. Referencing negative indices read from the end of the List, eg:

>>> sea_creatures
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']
>>> sea_creatures[-1]
‘anemone'

sea_creatures[-1] will return the last item in the list, anemone in this case.

Slicing Lists
The List data structure are mutable, meaning that in place changes of the structures content can occur. Slicing is one of the actions that can be taken on a List, which uses a colon(:) to specify a range of items to be acted on.

>>> sea_creatures[0:1]
['shark']

It is worth noting that in the above example, we referenced items with index 0 up to but NOT including 1.

Omitting either of the operands functions as a wildcard of sorts.

>>> sea_creatures[2:]
['squid', 'mantis shrimp', 'anemone’]
>>> sea_creatures[:2]
['shark', 'cuttlefish']

The Stride parameter specifies the interval of the items in the list to be retrieved. The syntax is in the form of list[x:y:z] with the Stride being Z.

>>> sea_creatures[0:5:2]
['shark', 'squid', 'anemone’]
>>> sea_creatures[::2]
['shark', 'squid', 'anemone']

Lists also support operators. The + and * operators can be used to concatenate and extend a List, respectively.

>>> sea_creatures1 = sea_creatures *2
>>> sea_creatures1
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone', 'shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone’]
>>> sea_creatures2
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone', 'horseshoe crab']

Compound operators such as += and *= are also available.

Deleting Items from the List
An item can be deleted in the following ways:

By index:

>>> del sea_creatures[1]
>>> sea_creatures
['shark', 'squid', 'mantis shrimp', 'anemone']

By Slice:

>>> del sea_creatures[0:1]
>>> sea_creatures
['squid', 'mantis shrimp', 'anemone']

Nested Lists
Lists can be nested, the end result being similar to a multidimensional array

>>> tic_tac_toe = [[0,1,2],[3,4,5],[6,7,8]]
>>> tic_tac_toe
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

The elements can be referenced by double square brackets [][], which function as row and column formats.

>>> tic_tac_toe[1][2]
5

Leave a Reply

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