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
2
  • 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? Commented Dec 9, 2020 at 7:13
  • @deceze you are correct Commented Dec 9, 2020 at 7:17

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.