2

Let's say i have three lists as follows:

letters = ['a', 'b', 'c']

numbers = ['1', '2', '3']

letters_numbers = ['a1', 'b2', 'c3']

And these three lists are pre-generated using list comprehension so there are not pre-defined. Therefore the number of items in these lists will differ depending on user input. But the number of items in each list will always be equal to the number of items in the other two lists.

Now, i want to use these three lists to create one big list that consists of LISTS and not tuples as follows:

big_list = [['a', '1', 'a1'], ['b', '2', 'b2'], ['c', '3', 'c3']]

I already tried doing this:

big_list = [[letter, number, letter_number] for [letter, number, letter_number] in [letters, numbers, letters_numbers]]

Which gave me this:

big_list = [['a', 'b', 'c'], ['1', '2', '3'], ['a1', 'b2', 'c3']]

Can you please tell me how i can achieve this? I specifically want to reach this result using only list comprehension.

But if there is another method to achieve this it will be highly appreciated along with the list comprehension method.

Elbasel
  • 240
  • 1
  • 10

3 Answers3

2

I was able to solve this using:



a = [1, 2, 3]

b = [4, 5, 6]

c = [7, 8, 9]

d = [[x,y,z] for x in a for y in b for z in c]

print(d)


Now I want to know if there is a better way or not?

Elbasel
  • 240
  • 1
  • 10
1

can you use zip?

>>> [[letter, number, letter_and_number] for letter, number, letter_and_number in zip(letters, numbers, letters_numbers)]
[['a', '1', 'a1'], ['b', '2', 'b2'], ['c', '3', 'c3']]
steviestickman
  • 1,132
  • 6
  • 17
1

Getting values into the lists like you want is usually done with the zip() function.

In order to convert the tuples (output of zip function) into lists you can then use a list comprehension as shown in thread Zip with list output instead of tuple

big_list = [list(a) for a in zip(letters, numbers, letters_numbers)]
shev.m
  • 43
  • 6