How do I join a list in Python?

5

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

So:

$a = [1, 2, 3];

$b = [4, 5, 6];

array_merge($a, $b);

Result:

  

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

And how could I do this in Python on 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];
    
asked by anonymous 13.08.2015 / 14:12

2 answers

5

You can simply add both:

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

See running on ideone .

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

Just remember that you do not have ; in Pyhton:)

    
13.08.2015 / 14:22
4

You can use extend() . Example:

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

Result:

  

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

More information on list methods: Pythons Docs - Data Structures

    
13.08.2015 / 14:16