0

I have a list below. I need to use it to create a new nested list with only the first element in the sublist with the last element in list.

a=[[a,b,c],3]

the outcome should look like

b=[[a,3],[b,3],[c,3]]
1
  • 1
    Should a=[[a,b,c],3] be a=[['a','b','c'],3]? Commented May 5, 2018 at 10:35

2 Answers 2

1

Use zip():

In [79]: a=[['a','b','c'],3]

In [80]: list(zip(a[0], [a[1]]*len(a[0])))
Out[80]: [('a', 3), ('b', 3), ('c', 3)]

Or:

In [83]: (a, b, c), num = a

In [84]: [(a, num), (b, num), (c, num)]
Out[84]: [('a', 3), ('b', 3), ('c', 3)]

Or more general:

In [85]: lst, num = a

In [86]: from itertools import repeat

In [87]: list(zip(lst, repeat(num, len(lst))))
Out[87]: [('a', 3), ('b', 3), ('c', 3)]

Another way is using a nested list comprehension:

In [15]: a
Out[15]: [['a', 'b', 'c'], [1, 2]]

In [16]: [(j, i) for i in a[1] for j in a[0]]
Out[16]: [('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2)]
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, it works fine, thanks a lot, but do i have to do some changes if a =[['a','b','c'],[1,2]] and the output looks like a=[('a',1),('b',1),('c',1),('a',2),('b',2),('c',2)]
If the order is not important you can simply use itertools.product. list(product(*a)). Or check the update.
WELL, Thanks a lot, you helped me a lot, i appreciate your effort.
1

You can use a list comprehension:

>>> a = [['a','b','c'], 3]
>>> sublist, value = a
>>> [[x, value] for x in sublist]
[['a', 3], ['b', 3], ['c', 3]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.