-2

given a nested list:

input_list = [['c', 'd'], ['e', 'f']]

addition_to_input_list = ['a', 'b']

required_output = [['a', 'b'], ['c', 'd'], ['e', 'f']]

for my current program, it is enough to put the addition at the start, in the future I may have to also put the addition at a specific index in the nested list.

Thanks in advance

mozway
  • 194,879
  • 13
  • 39
  • 75
Zenith_1024
  • 231
  • 2
  • 14

1 Answers1

0

This is a simple list insertion. It doesn't matter that the elements are lists themselves. So, this will do it:

input_list.insert( 0, addition_to_input_list )

Or you can build a new list:

required_output = [addition_to_input_list] + input_list

Proof that both options work:

>>> input_list = [['c', 'd'], ['e', 'f']]
>>> addition_to_input_list = ['a', 'b']
>>> input_list.insert(0,addition_to_input_list)
>>> input_list
[['a', 'b'], ['c', 'd'], ['e', 'f']]

>>> input_list = [['c', 'd'], ['e', 'f']]
>>> [addition_to_input_list]+input_list
[['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> 
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Hey, when i do the above mentioned method, i get this as the output current_output = ['a', 'b', ['c', 'd'], ['e', 'f']] but i want the list ['a', 'b'] to be added as a sublist, required_output = [['a', 'b'], ['c', 'd'], ['e', 'f']] – Zenith_1024 Nov 22 '21 at 07:31
  • Then you made a typo. Both of my commands work exactly as they are presented. I'm guessing you tried the second example but did not include the brackets around the first list. – Tim Roberts Nov 22 '21 at 07:39