0

Let's say I have a tuple that is (4, 5, 6, 7, 8). I want to iterate through it, then each iteration only print the numbers after that index. So like this:

for i in tuple:
    #print values to the right of i

Example output: 5, 6, 7, 8, 6, 7, 8, 7, 8, 8. Any help? I know how to access a tuple value by its index but not by the reverse.

0

4 Answers 4

6

Do you mean something like this?

t = (4, 5, 6, 7, 8)
for i, _ in enumerate(t, 1):
  print(t[i:])

# (5, 6, 7, 8)
# (6, 7, 8)
# (7, 8)
# (8,)
# ()

If you want to join them all into an output tuple, the following 1-liner will do it inefficiently:

>>> sum((t[i:] for i, _ in enumerate(t, 1)), ())
(5, 6, 7, 8, 6, 7, 8, 7, 8, 8)

A more efficient way would be to use itertools.chain.from_iterable:

tuple(itertools.chain.from_iterable(
    t[i:] for i, _ in enumerate(t, 1)))
Sign up to request clarification or add additional context in comments.

Comments

0

Try

tuple = (4,5,6,7,8)
z = []
for i in range(len(tuple)):
    for j in tuple[i+1:]:
        z.append(j)

output is [5,6,7,8,6,7,8,7,8,8]

2 Comments

do you mean z.extend(j)? appending will result in a list with tuples as items.
this is appending the individual items of the tuple, not the tuple itself.
0

According to the Python documentation, tuples are immutable objects. So if you want to change the output that you produce each time you iterate through the tuple, you will need to set a new variable in your loop each time. Something like this:

t = (5,6,7,8)
for i,n in enumerate(t):
    tnew = t[i:]
    print tnew

Comments

0

Using a list comprehension:

t = (4, 5, 6, 7, 8)
>>> [i for n in range(len(t)) for i in t[n+1:]]
[5, 6, 7, 8, 6, 7, 8, 7, 8, 8]

Or if you want a tuple, you can use a generator expression (tuple comprehension?):

>>> tuple(i for n in range(len(t)) for i in t[n+1:])
(5, 6, 7, 8, 6, 7, 8, 7, 8, 8)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.