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
  • 39,034
  • 24
  • 81
  • 124
fdmillion
  • 4,436
  • 6
  • 39
  • 74
  • 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
  • 21,645
  • 4
  • 39
  • 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
  • 39,034
  • 24
  • 81
  • 124
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
  • 281,034
  • 50
  • 354
  • 495
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
  • 39,034
  • 24
  • 81
  • 124
aayoubi
  • 10,299
  • 3
  • 19
  • 20