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

Viewed 224

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.

5 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", )]

The problem is that you are not defining a proper tuple. Your iteration is fine.

But you have:

test_list = [("rock", "paper", "scissors"),("go","fish"),("uno")]

When you should have:

test_list = [("rock", "paper", "scissors"),("go","fish"),("uno",)]

Note the extra comma. Without it, the parentheses wrapping "uno" are effectively ignored, and "uno" the string becomes the item iterated, which yields individual characters.

This is simply a requirement for specifying single element tuples in Python.

uno is not a tupple in your scenario. to make it a tuple change it to:

test_list = [("rock", "paper", "scissors"),("go","fish"),("uno",)]

note the added coma after uno

You got a lot of great answers to your original question. Separately, you might be interested to know that the chain function from the the itertools standard library is convenient for the type of iteration you are performing and might be worth considering.

Example:

from itertools import chain

test_list = [("rock", "paper", "scissors"),("go","fish"),("uno",)]

for each_word in chain.from_iterable(test_list):
    print(each_word)

Output:

rock
paper
scissors
go
fish
uno

To achieve the required output just put a coma after "uno", like this.

("uno",)
Related