If we write a code like:

a=
a1=len(a)
a2=range(a1)
for x in a2:
a3=a[x]
print a3

In this code if we want to store the value of a3 it would store last value always. But in any way can we store all the values?

Recommended Answers

All 3 Replies

To copy a list you would use
a3 = a[:]
print a3

If you don't want an exact copy you would append to another list

a=['city','village','town','capital']
a3=[]
for x in a:
   print "x in a =", x
   if x.startswith( "c" ):
      print "     appending", x, "to a3"
      a3.append(x)
print a3

Dear Sir,
Just thanx. I was thinking to create a blank list and appending it there but somehow it was not working.
Thank you for giving me the time,
Subhabrata Banerjee.

I am not quite sure what you mean with store, If you mean store in a string, there are these ways:

a=['city','village','town','capital']
a1=len(a)
a2=range(a1)
s = ""
for x in a2:
    a3=a[x]
    print a3
    s += a[x]

print s  # cityvillagetowncapital

Much simpler:

a=['city','village','town','capital']
s = ""
for x in a:
    s += x

print s  # cityvillagetowncapital

Add a space separator:

a=['city','village','town','capital']
s = ""
for x in a:
    s += x + " "  # add a space

print s  # city village town capital

Even simpler:

a=['city','village','town','capital']
s = " ".join(a)
print s  # city village town capital

Note: I hope Dani does not think those annoying HSBC popup ads are an improvement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.