In Python, how to pick a random sub sequence of consecutive elements in a list?
In Python, to pick a random sub sequence of consecutive elements in a given list, the best option is to pick two random values (left
and right
) and then to extract the sub list with the syntax myList[left:right]
. Here is a full example that pick 20 sub sequances:
from random import randint
# List
myList = [1,2,3,4,5,6,7,8,9,10]
# Left and right indexes are picked randomly
left = randint(0, len(myList)-1)
right = randint(left+1, len(myList))
# extract sub list
sub = myList[left:right]
print (sub)
Here are some examples of output:
[4]
[5, 6, 7, 8]
[6, 7, 8]
[5, 6, 7, 8, 9, 10]
[3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1]
[5]
[8, 9]
[2]
[5, 6, 7, 8]
[10]
[5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
[6, 7, 8]
[6, 7]
[6, 7, 8, 9, 10]
[1, 2, 3]
[2, 3, 4, 5, 6, 7, 8]
In Python, to pick a random sub sequence of consecutive elements in a given list, the best option is to pick two random values (left
and right
) and then to extract the sub list with the syntax myList[left:right]
. Here is a full example that pick 20 sub sequances:
from random import randint
# List
myList = [1,2,3,4,5,6,7,8,9,10]
# Left and right indexes are picked randomly
left = randint(0, len(myList)-1)
right = randint(left+1, len(myList))
# extract sub list
sub = myList[left:right]
print (sub)
Here are some examples of output:
[4]
[5, 6, 7, 8]
[6, 7, 8]
[5, 6, 7, 8, 9, 10]
[3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1]
[5]
[8, 9]
[2]
[5, 6, 7, 8]
[10]
[5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
[6, 7, 8]
[6, 7]
[6, 7, 8, 9, 10]
[1, 2, 3]
[2, 3, 4, 5, 6, 7, 8]
In Python, to pick a random sub sequence of consecutive elements in a given list, the best option is to pick two random values (left
and right
) and then to extract the sub list with the syntax myList[left:right]
. Here is a full example that pick 20 sub sequances:
from random import randint
# List
myList = [1,2,3,4,5,6,7,8,9,10]
# Left and right indexes are picked randomly
left = randint(0, len(myList)-1)
right = randint(left+1, len(myList))
# extract sub list
sub = myList[left:right]
print (sub)
Here is some example of outputs:
[4]
[5, 6, 7, 8]
[6, 7, 8]
[5, 6, 7, 8, 9, 10]
[3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1]
[5]
[8, 9]
[2]
[5, 6, 7, 8]
[10]
[5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
[6, 7, 8]
[6, 7]
[6, 7, 8, 9, 10]
[1, 2, 3]
[2, 3, 4, 5, 6, 7, 8]
# | ID | Query | URL | Count |
---|