Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a list of string tuples of varying lengths in Python?

Tags:

python

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.

like image 256
Raaid Avatar asked Dec 01 '22 08:12

Raaid


1 Answers

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", )]
like image 112
Prune Avatar answered Dec 06 '22 10:12

Prune