1

I define:

A = [[1, 2], [3, 4], [5, 6]]

What is/are the line/s producing:

B = [['hello', [1, 2]], ['hello', [3, 4]], ['hello', [5, 6]]]
Inder
  • 3,711
  • 9
  • 27
  • 42

2 Answers2

7

You can add 'hello' to the front of each list with a list comprehension:

>>> add = 'hello'
>>> A = [[1, 2], [3, 4], [5, 6]]
>>> [[add, x] for x in A]
[['hello', [1, 2]], ['hello', [3, 4]], ['hello', [5, 6]]]
# or [[add] + [x] for x in A]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • I got my actual use case thanks to your answer + the zip function pointed by @VladimirPogosyan + this article: [link](https://stackoverflow.com/questions/5850986/joining-pairs-of-elements-of-a-list-python) – Robin Tournemenne Jul 22 '18 at 11:48
  • @RobinTournemenne Feel free to accept an answer by clicking the green checkmark next to it if the problem has been solved! Thanks. – timgeb Oct 18 '18 at 16:57
4

This may be helpful:

B = zip(['hello'] * len(A), A)

This will produces following result: [('hello', [1, 2]), ('hello', [3, 4]), ('hello', [5, 6])] If you need lists instead of tuples, you can use following code:

B = list(map(list, zip(['hello'] * len(A), A)))