How do I join a list in Python?

Asked

Viewed 15,912 times

8

When I want to unite a array in PHP, I use the function array_merge

Thus:

$a = [1, 2, 3];

$b = [4, 5, 6];

array_merge($a, $b);

Upshot:

[1, 2, 3, 4, 5, 6]

And how could I do that in Python in a list (I think a list is equivalent to array in PHP, if I’m not mistaken)?

Example:

a = [1, 2, 3]

b = [4, 5, 6];

2 answers

9


You can just add the two:

a = [1, 2, 3]
b = [4, 5, 6]
print (a + b)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Python overloads operators as much as possible to make them more intuitive and short. Some disagree that this is more intuitive but many find it quite obvious.

Just don’t forget you don’t have ; in Pyhton :)

  • I always forget that I’m not in PHP! there are problems if I forget one ; down in the code?

  • 1

    It is accepted without causing problems because you may want to put several statements on the same line. But it gets weird to use at the end of the single line.

  • ... Since in python the organization is made by identation... Full sentence

  • Cloudflare is screwing with me today, I’m late because I can’t access the site. It’s been almost a week. http://meta.pt.stackoverflow.com/q/4225/101

8

You can use the extend(). Example:

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print a

Upshot:

[1, 2, 3, 4, 5, 6]

More information about list methods: Pythons Docs - Data Structures

  • I thought you’d say something else, but it was nice to meet extend

  • What do you mean "something else"? rs.. I didn’t understand if the solution meets or not.

  • No, answer yes, friend, @Math. I thought you were going to answer +. Very good, I didn’t know I could do that

  • In this case, it would be like + to create a variable c with both values, without changing the original?

  • Ah, great :) Now I understand what you mean by "changing the way you display the result"

  • I hope you understand that I marked the @bigown response because of the question of keeping the original variable at the same value :)

  • @Wallacemaxters no problem man! Have to mark the one that best suits you even :)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.