John Smith
John Smith

Reputation: 6259

Add values to array in one line

How can I write this code in one-line?

aa = []
for s in complete:
    aa.append(s)

I know there are several solutions. I would really appreciate if you could write them down. Thanks!

Upvotes: 2

Views: 3827

Answers (6)

ailin
ailin

Reputation: 501

like this (be care with strings):

aa.extend(complete)

or with list comprehension:

aa = list(s for s in complete)

or if u want to copy list u can do follow:

aa = complete[:]
aa = complete.copy() # same
aa = list(complete) # same

or just use '+':

aa += complete

Upvotes: 2

cameronroytaylor
cameronroytaylor

Reputation: 1659

As long as you just need to set aa equal to complete, just use

aa = complete

Upvotes: 2

lensonp
lensonp

Reputation: 423

I like to do such things with a list comprehension:

aa = [s for s in complete]

Though, depending on the type of complete, and whether or not you want to use package like numpy there may be a faster way, such as

import numpy as np
aa = np.array(complete)

I'm sure there are many other ways as well :)

Upvotes: 1

Vaibhav Bajaj
Vaibhav Bajaj

Reputation: 1934

To extend aa, use the extend() function:

aa.extend(s for s in complete)

or

aa.extend(complete)

If you simply wanted to equate the two, a simple = is fine:

aa = complete

Upvotes: 0

robert.otherone
robert.otherone

Reputation: 48

If you want to add values to array in one line, it depends how the values are given. If you have another list, you can also use extend:

my_list = []
my_list.extend([1,2,3,4])

Upvotes: 0

joaquinlpereyra
joaquinlpereyra

Reputation: 966

List comprehensions are awesome:

aa = [s for s in complete]

Upvotes: 2

Related Questions