简体   繁体   中英

Python 3: how to add a certain group of items to list1 from list2?

How do you add a certain group of items from list1 to list2 in one go ? (so no for loops)

So eg:

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

Now I'd like to add the first 3 items from list1 to list 2, so the end result would be: list2 = [1,2,3,4,5,6,7]

I know you can remove a certain group of items from a list, but how do you move them? Thanks!

You can do this way using list slice [:3] and .extend() ,

list1 = [5,6,7,8]
list2 = [1,2,3,4]
list3 = list2[:3]
list3.extend(list1)
print(list3)

DEMO: https://rextester.com/NPD40369

To get the last 3 elements from list2 use, list2[-3:]

Sometimes it's more simple than we think. Use this to add the first three elements:

list2.extend(list1[:3])

And per your comment, use this to add the last three:

list2.extend(list1[-3:])

You can use a list slice , link to introduction to python, a good page for questions such as this.

Which would look like the following:

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

list2 += list1[:3]
print(list2)

Output:

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

Remember with slices it's from but not including index, up to and including index. For example

list2 += list1[2:3]

Would be:

[1,2,3,4,7]

你可以连接列表

list2 += list1[:3]

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