3

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']
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

5

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

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • I didn't know slices could have 4 things in them. I thought it was just start end and step. – Ogen Apr 16 '15 at 15:01
  • Been in python since 2.3: https://docs.python.org/2.3/whatsnew/section-slices.html – EdChum Apr 16 '15 at 15:02
  • @Ogen: none of these have four things in them, they all have three. `l[1::2]` is `l[start:(end):step]` with `start=1`, `end=None`, and `step=2`. – DSM Apr 16 '15 at 15:04
  • @Ogen it is just start, end and step - what's the 4th? – Ben Apr 16 '15 at 15:05
  • Whoops, my mistake, I got confused because the words slice had 3 characters in it while the hints one had 4. I forgot they've just omitted stuff. – Ogen Apr 16 '15 at 23:52