Sep-30-2022, 09:19 PM
(This post was last modified: Sep-30-2022, 09:22 PM by deanhystad.)
You can use zip. Zip is one of my favorite Python functions. I use it all the time.
https://docs.python.org/3/library/functions.html#zip
In the code below I use zip and a list comprehension to make a list of lists.
And finally I pair up letters and numbers in a dictionary. You may have a good reason for making lists of lists (or tuples), but you should consider using a dictionary.
https://docs.python.org/3/library/functions.html#zip
In the code below I use zip and a list comprehension to make a list of lists.
numbers = ["1", "2", "3", "5"] letters = ["a", "b", "c", "d", "e"] pairs = [[letter, number] for letter, number in zip(letters, numbers)] print(pairs)
Output:[['a', '1'], ['b', '2'], ['c', '3'], ['d', '5']]
if you don't understand how a list comprehension works, this is the list code written using a for loop.pairs = [] for letter, number in zip(letters, numbers): pairs.append([letter, number]) print(pairs)
Output:[['a', '1'], ['b', '2'], ['c', '3'], ['d', '5']]
You can also use the built-in list() function.pairs = list(zip(letters, numbers))
Output:[('a', '1'), ('b', '2'), ('c', '3'), ('d', '5')]
Notice that list() makes tuples instead of lists. A tuple is like a list, but you can't modify the contents of a tuple. However, tuples have an advantage in speed and memory usage.And finally I pair up letters and numbers in a dictionary. You may have a good reason for making lists of lists (or tuples), but you should consider using a dictionary.
pairs = dict(zip(letters, numbers))
Output:{'a': '1', 'b': '2', 'c': '3', 'd': '5'}