Search code examples
pythonconcatenation

Incorporating instance 'count' into list joined into string (Python3)


First time asking a question on SO, so please bear with me.

In the python program I'm writing, I am trying to avoid concatenation of a string in a for loop by using the join method (because: efficiency), but I would like for the program to put a count next to each instance.

For example:

[1] First item [2] Second item [3] Third item

From what I understand (I'm not a master pythoner), this form of using .join() is utilizing a list comprehension, and I can't seem to figure out the proper syntax to do what I'm trying to.

temporary_list = ["First item", "Second item", "Third item"]
count = 1
display = "\n".join("> [{}] {}".format((count), t), count += 1 for t in temporary_list[:10])

I could easily do this with a for loop:

    for t in temporary_list[:10]:
            display += "> [{}] {}\n".format(count, t)
            count += 1

I have a similar line of code that works fine without counting.

display = "\n".join("> {}: {}".format(t, display_correctly(number_list[t])) for t in temporary_list[:10])

I've tried playing with the parenthesis, using 'and' and a lot of googling. Is there a way to do this?

If it matters, I'm using python 3.6


Solution

  • IIUC, you need enumerate:

    temporary_list = ["First item", "Second item", "Third item"]
    print("\n".join("> [{}] {}".format(n, i) for n, i in enumerate(temporary_list, start=1)))
    

    Output:

    > [1] First item
    > [2] Second item
    > [3] Third item