-2

I am trying to loop through a list and make a variable that contains the list + some other info to be able to use it outside the for loop, however when I print my variable outside the loop I only get the last item in the list. I want to see all of them in the list.

#!/usr/bin/python
a = ['apple', 'orange', 'peanut']
for item in a:
    mylist = '*' + item
    print item

print "------out of loop ----------"
print mylist

The output is:

apple
orange
peanut
------out of loop ----------
*peanut
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
SteelerKid
  • 304
  • 1
  • 4
  • 15
  • Are you expecting `'*' + item` to be some sort of list operation? That's not something I'm familiar with in python. Perhaps you mean to `.append(item)` to the list instead? – G. Anderson Jun 17 '19 at 20:10

2 Answers2

1

you have to declare mylist outside of the loop. also you need to use '+=' (append) to keep adding onto mylist

a = ['apple', 'orange', 'peanut']
mylist = ''
for item in a:
    mylist += '*' + item
    print(item)

print("------out of loop ----------")
print(mylist)

this output should be :

apple
orange
peanut
------out of loop ----------
*apple*orange*peanut
0

With mylist = '*' + itemyou always overwrite the old value of mylist

If you want to keep it, you should do something like mylist = mylist + '*' + item , depending on what you want to display

Or a different solution would be mylist += '*' + item

Robinbux
  • 59
  • 1
  • 7