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
anda
,1
andb
,1
andc
2
anda
,2
andb
,2
andc
3
anda
,3
andb
,3
andc
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:
Our desire is to get something like:
1
and500
2
and600
3
and700
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