I am working to increment lists in such a way that each item in the list is incremented incrementally, it sounds confusing but its not:

If the user inputs:

list = [1, 2, 3, 4]

I want the output to be:

2, 4, 6, 8

in essence, the first item gets 1 added, the second gets 2 added, the third gets 3, and so on.

Recommended Answers

All 7 Replies

Hi Carlo Gambino,

The straightforward way of doing this is:

g = [ 1, 2, 3, 4 ]
h = []
for i in range(len(g)+1)[1:]:
    h.append(g[i-1]+i)
print h

Alternatively, you could just use a list comprehension:

print [ g[i-1]+i for i in range(len(g)+1)[1:] ]

Hope this helps!

Well this certainly has helped, and it is accomplishing what I want. I'm having trouble understanding how this code works. I tried to play around with this a little bit to change the incrementation by one:

for user input:

aaaaa

the output should be:

abcde

Incrementing starts a 0 rather than 1.

Thanks for the help so far! This has been a very educational project.

You can use the enumerate function and incrementally increment the ascii value of the character ...

s = 'aaaa'

q = ""
for ix, e in enumerate(s):
    q += chr(ord(e) + ix)

print q  # abcd

For your first problem you could use something similar ...

a = [1, 2, 3, 4]

# since you want a list use a list comprehension
b = [(e + 1 + ix) for ix, e in enumerate(a)]

print b  # [2, 4, 6, 8]

I'm not sure I totally understand the enumerate function, but once I have solved this problem I will certainly learn.

If you want to familarize yourself with a function, it helps to print some of the results:

# enumerating over a string or list returns the index and the element

s = 'help'

for ix, c in enumerate(s):
    print ix, c

"""
my result -->
0 h
1 e
2 l
3 p
"""

Using a for loop might be easier to understand.

test_list=[1,3,5,7]
ctr = 0
stop=len(test_list)
for j in range(0, stop):
      ctr += 1
      before_add = test_list[j]
      test_list[j] += ctr     ## ctr = j+1 in this specific case
      print "element", j, "did =", before_add, "and now =", test_list[j]
print "\n", test_list

And don't forget to understand the underlying math. If you're incrementing each value by its own value, then what you get is twice that value:

a = [1,2,3,4]

b = [2*x for x in a]

OR if you are incrementing each value by its place in the list,

a = [4,5,6,7]

b = [x + a.index(x) + 1 for x in a]
# b = [5, 7, 9, 11]

Depending on the design parameters for your list, a little deep thought might lead to a simpler algorithm.

Jeff

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.