{"id":25520,"date":"2021-11-19T09:12:50","date_gmt":"2021-11-19T03:42:50","guid":{"rendered":"https:\/\/python-programs.com\/?p=25520"},"modified":"2021-11-19T09:12:50","modified_gmt":"2021-11-19T03:42:50","slug":"python-random-choices-method-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-random-choices-method-with-examples\/","title":{"rendered":"Python Random choices() Method with Examples"},"content":{"rendered":"

Random choices() Method in Python:<\/strong><\/p>\n

The choices() method returns a list containing the element from the specified sequence that was chosen at random.<\/p>\n

You can use the weights or cum weights parameters to weigh the likelihood of each result.<\/p>\n

The sequence could be a string, a range, a list, a tuple, or anything else.<\/p>\n

Syntax:<\/strong><\/p>\n

random.choices(sequence, weights=None, cum_weights=None, k=1)<\/pre>\n

Parameters<\/strong><\/p>\n

sequence:<\/strong> This is Required. It could be a list, a tuple, a range of numbers, and so on.<\/p>\n

weights:<\/strong> This is Optional. A list where you can weigh the pros and cons of each value.
\nNone is the default.<\/p>\n

cum_weights:<\/strong> Optional. A list in which you can weigh the possibility for each value, except that this time the possibility is accumulated.
\nFor instance, the normal weights list [2, 1, 1] is the same as the cum weights list [2, 3, 4].
\nNone is the default.<\/p>\n

k:<\/strong> This is Optional. An integer that specifies the length of the returned list.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List = [\"good\", \"morning\", \"all\"]\r\nGiven weights = [5, 1, 1]\r\nGiven k value = 10<\/pre>\n

Output:<\/strong><\/p>\n

['good', 'all', 'good', 'good', 'good', 'morning', 'good', 'good', 'good', 'good']<\/pre>\n

Explanation:<\/strong><\/p>\n

Return a list containing 10 items.\r\nThe list should contain a random selection of values from a given list, with\r\nthe possibility of selecting \"good\" being 5 times greater than the other two<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List = [1,2,3]\r\nGiven weights = [1,1,3]\r\nGiven k value = 12<\/pre>\n

Output:<\/strong><\/p>\n

[2, 1, 3, 3, 3, 2, 3, 3, 3, 2, 2, 3]<\/pre>\n

Explanation:<\/strong><\/p>\n

Return a list containing 12 items.\r\nThe list should contain a random selection of values from a given list, with \r\nthe possibility of selecting \"3\" being 3 times greater than the other two<\/pre>\n

Random choices() Method with Examples in Python<\/h2>\n