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!
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With