-2

In a Python script I'm writing, I have a function that can only output its results in a nested tuple, like so:

(('foo',), ('bar',), ('baz',), ('spam',), ('eggs',))

I need to structure a FOR loop so that I can use the tuple (as a tuple for immutability, not individual strings) like so:

('foo', 'bar', 'baz', 'spam', 'eggs')

I'm new to coding (let alone Python), and I've never had a special proclivity for loops anyway, but I'm pretty sure that I'll need to use enumerate() to pull out the 0th entries from each nested tuple, and put those in a new(?) tuple. This is the code I have...

for count,item in enumerate(tuple):
    s = item[0]
    item = tuple[count]

Any help or suggestion would be appreciated!

A. Galloway
  • 135
  • 1
  • 10

2 Answers2

0

In Python, you can write:

a, b = ('some', 'tuple')

to get the individual values out of a tuple. You can do the same thing in a for loop. In your case, each tuple only has one value, so you just need one variable on the left-hand side. (Note the comma!)

stuff = (('foo',), ('bar',), ('baz',), ('spam',), ('eggs',))

for item, in stuff:
    print(item)

# Output:
# foo
# bar
# baz
# spam
# eggs

EDIT

Per the comments, putting the items into a tuple instead:

values = tuple(item for item, in stuff)
print(values)

# Output:
# ('foo', 'bar', 'baz', 'spam', 'eggs')
user94559
  • 59,196
  • 6
  • 103
  • 103
0

You can construct a tuple from any iterable, like this:

tuples = (('foo',), ('bar',), ('baz',), ('spam',), ('eggs',))
values = tuple(t[0] for t in tuples)
print(values)
# -> ('foo', 'bar', 'baz', 'spam', 'eggs')

A tuple in Python is non-mutable. If you need a mutable collection, use a list.

To do that, you can use a comprehension list:

values = [t[0] for t in tuples]
print(values)
# -> ['foo', 'bar', 'baz', 'spam', 'eggs']

Consult the online documentation, to know more about Data Structure and List Comprehensions

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103