Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose 5 different elements from a list?

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

Thanks for the help!

like image 648
Andrew Avatar asked Jan 05 '11 06:01

Andrew


People also ask

How do you randomly select 5 items from a list in Python?

Select randomly n elements from a list using choice() The choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).

How many different elements are in a list?

The periodic table of elements is widely used in the field of Chemistry to look up chemical elements as they are arranged in a manner that displays periodic trends in the chemical properties of the elements.


1 Answers

Assuming that you want them chosen randomly and that new_list is already defined,

import random

new_list += random.sample(old_list, 5)

If new_list is not already defined, then you can just do

new_list = random.sample(old_list, 5)

If you don't want to change new_list but want to instead create new_new_list, then

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

Now references to new_list will still access a list without the five new elements but new_new_list will reference a list with the five elements.

like image 105
aaronasterling Avatar answered Oct 09 '22 12:10

aaronasterling