Python Randomly Select Elements From List

Python Randomly Select Elements From List

Python randomly selects an element or item from list. In this tutorial, you will learn how to randomly select single or n element from a list in python.

As well as, this tutorial will help you to selecting random element from list python without repetition.

Python Randomly Select Elements From List

  • Python randomly select item or element from the list
  • Python randomly select n elements from the list

Python randomly select item or element from the list

To select random items from a list in Python, you will use the random.choice() method. The random choice() is a built-in method that returns a random item from the non-empty sequence-like list. To use the choice() method in your program, you need to import the random package in your file.

import random

Now follow the following instructions to select randomly element or item from list in python.

  • First of all, import random in your python program.
  • Then declare list of items.
  • Use random.choice(data) with list of itmes.
  • At the last of program print result.
import random

data = ["samsung", "tata", "amazon", "flipkart", "mi"]

print(random.choice(data))

After executing the program, the output will be:

amazon

Python randomly select n elements from the list

To select random items from a list in Python, you will use the random.sample() method. The random sample() is a built-in method that returns a random items from the non-empty sequence-like list.

Note that, The random.sample() method accepts two arguments which are a list or set and the number of elements, and returns the sample elements.

Now follow the following instructions to select randomly multiple elements or items from list in python.

  • First of all, import random in your python program.
  • Then declare list of items.
  • Use random.select(data) with list of itmes.
  • At the last of program print result.
import random

data = ["samsung", "tata", "amazon", "flipkart", "mi"]

print(random.select(data, 2))

If you want to select 2 random elements from the list, and then you will pass 2 as the second argument, which suggests the number of elements you need in the list.

After executing the program, the output will be:

['samsung', 'flipkart']

Recommended Python Programs

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *