AKor
AKor

Reputation: 8882

Python accessing tuple index by value

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.

Upvotes: 0

Views: 2611

Answers (4)

Alexander
Alexander

Reputation: 109546

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)

Upvotes: 0

Jon
Jon

Reputation: 155

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

Upvotes: 0

nathan.medz
nathan.medz

Reputation: 1603

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]

Upvotes: 0

mgilson
mgilson

Reputation: 309929

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)))

Upvotes: 6

Related Questions