Suppose i have a list l=[1,2,3]
i want to make this list as [2,3,4] i.e. add 1 to all the values in list l.
I want to do it by the method of for loop.. Can someone help?

Okay, I haven't been on in a while, let me tell you why no one has replied, you haven't showed ANY effort. Let me see the code you have so far and I'll tell you what you're doing wrong and give you suggestions. This is a simple solution, and you would get the answer in 2 seconds by looking at your text book or anyother reference and apply some logic.

I did it by List Comprehension method.

l=[1,2,3]
newlist=[x+1 for x in l]

This gives the correct output i.e a 'newlist' is formed with [2,3,4]

but in for loops, it is not coming,

l=[1,2,3]
for x in l:
newlist=[]
x+=1
newlist.append(x)

This gives a wrong output. A 'newlist' is formed not with [2,3,4] but with [4].

You must initialize the newlist out of the loop otherwise you reset before you add next one and you are left with the last value in the list.

Thank you!
By the way..i found one more solution

l=[1,2,3]
for x in range(len(l)):
l[i]+=1

I am getting the right output by this code too.

Sorry for a mistake in above reply, Instead of x in 2nd line of code, it should be i

So, The correct code is:

l=[1,2,3]
for i in range(len(l)):
l[i]+=1
#end

The one without indexes is considered often more 'pythonic', but of course sometimes it more usefull to use indexes. You lost your indention in posting code, put empty line and line with ~~~ before and opposite order after you code, or paint it after pasting and push Tab.

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.