0

I have a list which contains various company names I am trying to extract each item from the list and concatenate it to a string. Here is how i do it:

stock = ['TATACHEM', 'SNOWMAN']
for element in stock:
    z1='NSE:'+element

The Issue I face over here is that when I see z1 it contains only last element of the list concatenated with the string 'NSE' and the resulting output is:

NSE:SNOWMAN

However when I print all the element of the list it gives me all the elements. That is when I use:

for element in stock:
    print(element)

It gives me a list of both the elements in the list:

TATACHEM
SNOWMAN

How do I modify my code above so as to get the following output:

NSE:SNOWMAN
NSE:TATACHEM
Huzefa Sadikot
  • 561
  • 1
  • 7
  • 22
  • 1
    You *assign* to `z1`. `z1` can only hold a single value, so yes, the latter assignment overrides all previous assignments. Did you mean to create a new *list* into which you put those new strings? – deceze Dec 09 '20 at 07:13
  • @deceze you are correct – Huzefa Sadikot Dec 09 '20 at 07:17

1 Answers1

3

You could use z1 = "NSE: " + "\nNSE: ".join(stock)

Edit: If you want z1 as a list, then you could use list comprehension:

z1 = ["NSE:" + i for i in stock]
Keldan Chapman
  • 665
  • 5
  • 21