简体   繁体   中英

how to ADD a one list to another in python?

im trying to write a fun script for a password generator that DOES NOT have any rational connection to the user, thus making it alot harder to use the fact you know the user in order to guess it.. but im new to python

basically i know how to use append and extend but i was trying to find a way to add a whole list to another, for example is list1 is (1 2 3 4) and list2 is (3 4 5 9) i want to know how to add list2 to list1` and get a list1: (1 2 3 4 3 4 5 9)

ty!

This can be done very simply using the extend method. The following is a quick demonstration:

>>> l1 = [1,2,3]
>>> l2 = [3,4,5]
>>> l1.extend(l2)
>>> l1
[1, 2, 3, 3, 4, 5]

The addition operator has the same effect:

>>> l1 + l2
[1, 2, 3, 3, 4, 5]

Just use the concatenate overloaded operator:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 9]

list1 + list2
=> [1, 2, 3, 4, 3, 4, 5, 9]

The above will create a new list with the result of concatenating list1 and list2 . You can assign it to a new variable if necessary.

You have 2 ways (as far as I know). Let's:

list1 = [1,2,3]
list2 = [4,5,6]

First:

list1 = list1 + list2
print list3
>>> [1,2,3,4,5,6]

Second:

list1.extend(list2)
print list1
>>> [1,2,3,4,5,6]

Also remember that (1,2,3) is a tuple not a list .

加法连接列表:

list1 + list2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM