Python Forum
Creating list of lists, with objects from lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating list of lists, with objects from lists
#3
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.
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'}
Skaperen and sgrinderud like this post
Reply


Messages In This Thread
RE: Creating list of lists, with objects from lists - by deanhystad - Sep-30-2022, 09:19 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare lists w_i_k_i_d 4 194 May-18-2024, 04:03 PM
Last Post: Pedroski55
Question Using Lists as Dictionary Values bfallert 8 505 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  problem with print lists MarekGwozdz 4 778 Dec-15-2023, 09:13 AM
Last Post: Pedroski55
  python convert multiple files to multiple lists MCL169 6 1,684 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Lists blake7 6 878 Oct-06-2023, 12:46 PM
Last Post: buran
  Trying to understand strings and lists of strings Konstantin23 2 843 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Why do the lists not match? Alexeyk2007 3 895 Jul-01-2023, 09:19 PM
Last Post: ICanIBB
  ''.join and start:stop:step notation for lists ringgeest11 2 2,488 Jun-24-2023, 06:09 AM
Last Post: ferdnyc
  Need help with sorting lists as a beginner Realist1c 1 798 Apr-25-2023, 04:32 AM
Last Post: deanhystad
  Pip lists the module but python does not find it Dato 2 1,345 Apr-13-2023, 06:40 AM
Last Post: Dato

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020