Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a random element from a certain range in a list - python

I am creating a hangman game where i have a list that contains 5 secret words and a hint for each respective word that is read from a text file:

 list = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']

I need to create two separate lists only containing the secret words and hints respectively. How would I go about doing that?

desired outcome:

words = ['word1','word2','word3','word4','word5']
hints = ['hint1','hint2','hint3','hint4','hint5']
like image 955
Nick Gigler Avatar asked Jun 26 '26 19:06

Nick Gigler


1 Answers

Use slicing and the step notation to generate the two lists, l[::2] will step 2 elements starting from the first element whilst l[1::2] will also step 2 elements but starting from 2nd element:

In [145]:

l = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
words = l[::2]
hints = l[1::2]
print(words)
print(hints)
['word1', 'word2', 'word3', 'word4', 'word5']
['hint1', 'hint2', 'hint3', 'hint4', 'hint5']

The docs explain more about this

like image 174
EdChum Avatar answered Jun 28 '26 09:06

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!