Lists
22 May 2018Python’s basic collection data structure is the List. Much like an Array, a list is an ordered sequence of elements. Lists are mutable (they can be changed), and maybe most importantly, can store data of different types. For example here’s a list named “box”:
box = [5, True, [1,4], 42.5]
Our list includes an int, Bool, another list, and a float. This flexibility means we can add items dynamically as our program progresses.
In addition, we can reference a specific piece of data at a given index, or iterate through a list. A given operation can act on each element in order; let’s define a list of numbers, and figure out which ones are even and which are odd. Using the mod operator (% in Python) will give us the remainder left after dividing by a given number. By choosing mod 2, we’ll know which are odd by those that have non-zero values afterwards, like so:
numbers = [3 6 5 12 42]
for item in numbers:
print(item%2)
Which tells us only 3 and 5 are even:
1
0
1
0
0
[Finished in 0.0s]