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.

AKor
  • 8,550
  • 27
  • 82
  • 136

4 Answers4

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)))
mgilson
  • 300,191
  • 65
  • 633
  • 696
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]

nathan.medz
  • 1,595
  • 11
  • 21
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
Jon
  • 153
  • 1
  • 7
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)
Community
  • 1
  • 1
Alexander
  • 105,104
  • 32
  • 201
  • 196