I'm trying to iterate through a list of Tuples which are of varying length. However, I'm just trying to figure something out regarding it.
test_list = [("rock", "paper", "scissors"),("go","fish"),("uno")]
for each_tuple in test_list:
for each_word in each_tuple:
print(each_word)
This prints
rock
paper
scissors
go
fish
u
n
o
What is a solution I could use such that uno is printed as "uno" and not as u n o as separate letters. I understand why this is occuring, but I'm not sure what I should be implementing to "check" whether or not the tuple only has a single element in it vs. multiple.
This is a subtle distinction in Python syntax. Parentheses serve multiple purposes, most of the ones you'll see fall into one of three categories: (1) expression parentheses, as in changing the precedence order of arithmetic; (2) constructing a tuple; (constructing a generator).
test_list = [("rock", "paper", "scissors"),("go","fish"),("uno")]
Your first two pairs of parentheses have internal commas: they're obviously tuples. However, the third is more easily taken as a simple expression, so it evaluates to just the string:
test_list = [("rock", "paper", "scissors"),("go","fish"),"uno"]
To get what you want, force a one-element tuple with a simple comma:
test_list = [("rock", "paper", "scissors"),("go","fish"),("uno", )]
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