GhostCat
GhostCat

Reputation: 140427

How to declare an array using all elements of another array?

Assume I have a "constant" like:

ITEMS = [ "item1", "item2" ]

Now I would like to create an array that contains all entries of ITEMS, plus some more.

Obviously, this is wrong:

more_things = [ "all", ITEMS ]

as it would put the whole array into the new array. But I want the new array to contain [ "all", "item1", "item2" ] in the end.

Sure, I could somehow iterate the first array, but I am wondering if there is a more idiomatic one liner way to do this. Ideally, it should work for python2 and python3.

Upvotes: 1

Views: 86

Answers (5)

Eugene Yarmash
Eugene Yarmash

Reputation: 149746

If you're running Python 3.5+, the closest to your request is to use unpacking:

>>> ITEMS = ['item1', 'item2']
>>> ['all', *ITEMS]
['all', 'item1', 'item2']

In earlier versions list concatenation would do the same:

>>> ITEMS = ['item1', 'item2']
>>> ['all'] + ITEMS
['all', 'item1', 'item2']

If you simply need an iterable (i.e. not necessarily a list), using itertools.chain() may be more efficient:

from itertools import chain
more_things = chain(['all'], ITEMS)  # or wrap in list() to get a list

Upvotes: 2

cs95
cs95

Reputation: 402353

I'll suggest one more obvious approach: list.insert.

ITEMS.insert(0, 'all')
ITEMS
# ['all', 'item1', 'item2']

It modifies ITEMS in-place.


If you don't want to modify ITEMS, you can create a copy... although at that point, you'd rather one of the simpler options like iterable unpacking (*)...

ITEMS2 = ITEMS.copy()
ITEMS2.insert(0, 'all')

ITEMS2
# ['all', 'item1', 'item2']

Upvotes: 1

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

You can also use itertools.chain

from itertools import chain

more_things = list(chain(more_things, ITEMS))

it is useful when you want to add more than two lists together.

Upvotes: 0

javidcf
javidcf

Reputation: 59691

In Python 3 you can do:

ITEMS = [ "item1", "item2" ]
more_things = [ "all", *ITEMS ]

This is quite flexible because it lets you combine several lists (or iterables in general) and elements in one line:

even_more_things = [ "all", *ITEMS, "the", *ITEMS, "items" ]

Upvotes: 1

meowgoesthedog
meowgoesthedog

Reputation: 15035

Just concatenate them with +:

more_things = ["all"] + ITEMS

Upvotes: 2

Related Questions