Select 5 different items from the list?

What is the best way to select 5 different elements from a python list and add them to a new list?

Thanks for the help!

+4
source share
4 answers

Assuming you want them to be randomly selected and that new_list already defined,

 import random new_list += random.sample(old_list, 5) 

If new_list is not defined yet, you can simply do

 new_list = random.sample(old_list, 5) 

If you do not want to change new_list , but want to create new_new_list , then

 new_new_list = new_list + random.sample(old_list, 5) 

Now links to new_list will still access the list without five new items, but new_new_list will refer to a list with five items.

+11
source

Use random.sample call

 import random random.sample(yourlist,5) 
+2
source

You may need to be more specific, but to return 5 unique items from your list, you can simply use sample from a random module

 import random num = 5 aList = range(30) newList = [] newList+=random.sample(aList, num) 
+1
source
 >>> list = [1,3,6,3,2,5,7,4,7,8,9,4,3,2,4,6,7] >>> newlist = [] # Pick 5 and add to new list: >>> newlist.extend(list[:5]) >>> newlist [1, 3, 6, 3, 2] 
+1
source

Source: https://habr.com/ru/post/1334310/


All Articles