3

This may not be possible, but if it is, it'd be convenient for some code I'm writing:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']

If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo.

But instead, I want to expand ListOne into ListTwo, but I don't want to have to do something like:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox']
ListTwo.extend(ListOne)
ListTwo.extend(['lazy', 'dog!']

This will work but it's not as readable as the above code.

Is this possible?

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
fdmillion
  • 4,823
  • 7
  • 45
  • 82
  • What you want to do is to flatten the list. That's been covered here: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python and http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python and http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python and http://stackoverflow.com/questions/5409224/python-recursively-flatten-a-list – Sunita Venkatachalam Jul 16 '13 at 07:34

4 Answers4

8

You can just use the + operator to concatenate lists:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']

ListTwo will be:

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
grc
  • 22,885
  • 5
  • 42
  • 63
2

Another alternative is to use slicing assignment:

>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!']
>>> ListTwo[4:4] = ListOne
>>> ListTwo
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
1
>>> ListOne = ['jumps', 'over', 'the']
>>> from itertools import chain
>>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])]
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Why not concatenate?

>>> ListTwo = ['The', 'quick', 'brown', 'fox']
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo + ListOne
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the']
>>> ListTwo + ListOne + ['lazy', 'dog!']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
aayoubi
  • 11,285
  • 3
  • 22
  • 20