Lists

Lists are a way to organize data in such a way that the data can later be accessed sequentially or directly via indexing. Data can later be modified or utilized as necessary.

The syntax for defining a list is as follows:

list1 = [1, 2, 3, 4, 5]

Lists can contain variables of the same type, or they can contain variables of different types:

list2 = ['a', 1, 3.1]

The data stored in a list can be accessed via the data's corresponding "index", which is a number corresponding to a point of data in the list, numbered starting from 0.

This means that list1[1] would contain 2, and list2[0] would contain 'a'. list2[5] would be out of range, despite the list containing 5 points of data.

Lists can also be intialized as empty lists, meanign they don't yet contain anything.

list3 = []

To add to a list, either another list can be added to the previous list with the + operator, or the .append() list method can be used.

list3.append('a')
list3 += ['b'])
print(list3)
['a', 'b']

append adds a value to the end of the list; to add a value to the beginning of the list, or anywhere else for that matter, insert can be used.

list3.insert(0, 'c')
print(list3)
['a', 'b', 'c']

To transform other data types into lists, use list().

Other List-like Sequences

Tuples

Tuples are like lists, but immutable. They cannot be modified after assignment, although the tuple itself can be reassigned as a different variable as with any other variable. Desipte their name, they can hold more than two points of data.

tup = (1, 2)
tup2 = ('a', 'b', 4, 5)

To transform other data types into tuples, use tuple().

Sets

Sets are like lists, but are unordered, only store unique data, and are not subscriptable. This means that individual points of data cannot be accessed without first transforming the set into a list or another kind of subcriptable sequence.

set1 = {1, 2, 3, 4, 5}

set1[3] would result in a TypeError exception being thrown. See Errors section for information on exceptions.

Sets can be appended using the .add() set method, as follows:

set1.add(5)

This would do nothing, because set1 as shown further above already contains 5.

set1.add(6)

This would result in set1 containing {1, 2, 3, 4, 5, 6}.

To transform other data types into sets (in the process eliminating repeat values), use set().

Other

Dictionaries and Strings are also sequences, but are different enough from lists to warrant their own pages. Also, Lists can be 'sliced'. Check the Strings section for information on how to slice sequences.