2

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!

6 Answers 6

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

List comprehensions are awesome:

aa = [s for s in complete]

4 Comments

Thanks, was so close I had: aa = [for s in complete]
This does not append complete. Why not simply do aa = complete
@JohnSmith That's a syntax error, though. I find the [x for x in list] syntax somewhat awkward, seems redundant, but it makes sense when you want to add some logic to it: sayings = [country.saying for country in list_of_countries]
@VaibhavBajaj as the title of the questions suggests, I assume he wants to add values from a list to another. That's not exactly the same: he may want to add logic to 'filter' some values. But that's speculation on my part.
2

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

aa = complete

Comments

1

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 :)

Comments

0

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])

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.