Working with lists of data that pair up

You should have met nested for loops before. Where you have two sets of things and want access to all their pairings.

Say we have [1, 2] and ['a', 'b', 'c'] and we want all the different combinations of these. E.g.

  • 1 and a, 1 and b, 1 and c

  • 2 and a, 2 and b, 2 and c

  • 3 and a, 3 and b, 3 and c

This gives us 9 different pairings which each value being repeated. Maybe this is what you want, but sometimes the lists that we work with are connected in a different way.

Two equal sized lists

Instead of wanting to understand or measure something across all possible pairings in two groups, the values in each place are connected for some reason. Instead of wantitng to see each possible pairing, we want to see only the pairs that connect directly by placement.

We will be using lists of equal length to explore this, because that is the normal case.

Say we have:

left = [1, 2, 3]
right = [500, 600, 700]

Our desire is to get something like:

  • 1 and 500

  • 2 and 600

  • 3 and 700

What are a few things you can see here?

  • lack of repetition

  • the total number of pairs created match the length of both lists

Something to be mindful with these patterns is that you are inferring or creating a connection between the two pieces of content and the content positions. There is rarely a guarantee that this will always be the case. You should always check that you know where your lists came from and that they should be connected and their order correctly matches. Structures like dictionaries etc. will produce lists given certain methods, but you cannot (and should not) depend on the order those methods produce.

Code to add....

multiple lists in a single loop

  • mutual index values

  • zipping and other functional styles

Last updated