0

I have the following code

items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
for x in items:
    print(x, end='')
    print(items.index(x), end='')
## out puts: a0a0b2a0c4c4d6

I understand that python finds the first item in the list to index, but is it possible for me to get an output of a0a1b2a3c4c5d6 instead? It would be optimal for me to keep using the for loop because I will be editing the list. edit: I made a typo with the c indexes

3 Answers3

0

And in case you really feel like doing it in one line:

EDIT - using .format or format-strings makes this shorter / more legible, as noted in the comments

items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join("{}{}".format(e,i) for i,e in enumerate(items)))

For Python 3.7 you can do

items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join(f"{e}{i}" for i, e in enumerate(items)))

ORIGINAL

items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join((str(e) for item_with_index in enumerate(items) for e in item_with_index[::-1])))

Note that the reversal is needed (item_with_index[::-1]) because you want the items printed before the index but enumerate gives tuples with the index first.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Nathan
  • 9,651
  • 4
  • 45
  • 65
0

I think you're looking for a0a1b2a3c4c5d6 instead.

for i, x in enumerate(items):
    print("{}{}".format(x,i), end='')
tw0shoes
  • 167
  • 2
  • 8
-1

Don't add or remove items from your list as you are traversing it. If you want the output specified, you can use enumerate to get the items and the indices of the list.

items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
for idx, x in enumerate(items):
    print("{}{}".format(x, idx), end='')
# outputs a0a1b2a3c4c5d6
rma
  • 1,853
  • 1
  • 22
  • 42
  • 1
    Your first set of parenthesis are not needed and your are concatenation with `+` instead of `format()`. I would remove the parenthesis from `(idx, x)` to be more dry and note that `+` is deprecated over `format()`. – Mike - SMT Oct 21 '19 at 19:18
  • Almost there. You can remove `str()` as well as format handles the conversion. – Mike - SMT Oct 21 '19 at 19:31