Reputation: 23
I have a for loop with a tuple. I have attempted to print 't' and then print the elements in 't' but it continues to loop through t after each iteration. How do I print(t) once and then print(items) after?
t = ("tyler", 2.2, 3)
for item in t:
print(t)
print(items)
it runs
('tyler, 2.2, 3')
tyler
('tyler, 2.2, 3')
2.2
('tyler, 2.2, 3')
3
I have also tried calling the positions and it worked
>>> for items in t:
... print(t)
... print(t[0])
... print(t[1])
... print(t[2])
... break
('Tyler', 2.2, 3)
Tyler
2.2
3
Is there a more pythonic way of doing this?
Upvotes: 0
Views: 1418
Reputation: 1421
You have 3 items in t
, it means your loop will run 3 times.
You have 2 print statements, one that prints the entire tuple, and one that prints the current item.
If you want to print the tuple once, just move it outside of the for loop:
t = ("tyler", 2.2, 3)
print(t)
for item in t:
print(item)
('tyler', 2.2, 3)
tyler
2.2
3
You're second solution "works" because you break the loop after the first iteration, thus, you're only going through a single iteration, and not three...
Either that, or I don't understand what you're trying to accomplish
Upvotes: 3