{"id":25502,"date":"2021-11-23T08:56:08","date_gmt":"2021-11-23T03:26:08","guid":{"rendered":"https:\/\/python-programs.com\/?p=25502"},"modified":"2021-11-23T08:56:08","modified_gmt":"2021-11-23T03:26:08","slug":"python-random-sample-method-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-random-sample-method-with-examples\/","title":{"rendered":"Python Random sample() Method with Examples"},"content":{"rendered":"

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

The sample() method returns a list containing a randomly selected number of items from a sequence.<\/p>\n

Note:<\/strong> Please keep in mind that this method does not alter(change) the original sequence.<\/p>\n

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

random.sample(sequence, size)<\/pre>\n

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

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

size:<\/strong> This is Required. The number of items in the returned list.<\/p>\n

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

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

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

Given list = [4, 7, 9, 0, 1]\r\nGiven size = 3<\/pre>\n

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

The 3 random items from a given list =  [1, 9, 7]<\/pre>\n

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

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

Given list = [\"hello\", \"this\", \"is\", \"btechgeeks\"]\r\nGiven size = 2<\/pre>\n

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

The 2 random items from a given list =  ['is', 'btechgeeks']<\/pre>\n

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