How do I add a boolean value to each item in a list?

Viewed 159

thanks for taking the time to answer. I am making a hangman game as a beginner Python Project.\

I have the "word" that I split into a list, with each item being a character of the word.

word = "word" 
letters = []
letters[:] = word
print(letters)

["w","o","r","d"]

I am not quite sure how to assign a boolean value to each list item, creating tuples, like this:

[("w", False),("o", False), ("r", False), ("d", False)]

How do I go about doing this?

3 Answers

via list comprehension:

word = "word"
result = [(char, False) for char in word]

via map and lambda:

word = "word"
result = list(map(lambda x: (x, False), char))

I would go for using zip and list comprehension

word = ["w","o","r","d"]
booleanValues = [False,False,True,True]
lst = [(let,boo) for let,boo in zip(word,booleanValues)]

output

[('w', False), ('o', False), ('r', True), ('d', True)]

Now if you just wanted to assign False to each tuple, you could try the following.

word = ["w","o","r","d"]
lst = [(let,False) for let in word]

List comprehension

word = "word" 
letters = []
letters[:] = word
res = [(val, False) for val in letters]
print(res)




Related