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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With