AJDouglas
AJDouglas

Reputation: 35

For loop math with list

Say I have a hypothetical list such as:

my_list=['0','2','3','5','1']

I want to make a new list by having each number in my list subtract each other in a sequence to look something like this (each number subtracts to the left):

0-nothing=0
2-0=2
3-2=1
5-3=2
1-5=-4
new_list=['0','2','1','2','-4']

I feel like this could be solved in a for loop. Here's my terrible for loop, and me also doing it manually:

new_list = []
for item in my_list:
    new_list.append(float(item)) #Converting strings into floats

print(new_list)

#for number in my_list:
  #print(list(str((number-[0:])))) #completely wrong

new_list[0]=new_list[0]
new_list[1]=new_list[1]-new_list[0]
new_list[2]=new_list[2]-new_list[1] #Won't work past this point as the numbers in the list are now new.
new_list[3]=new_list[3]-new_list[2]
new_list[4]=new_list[4]-new_list[3]

print(new_list)

Each thing I try is a disaster. Am I going the wrong way with my substandard logic?

Upvotes: 3

Views: 805

Answers (5)

D.J
D.J

Reputation: 1312

Just because it was fun to do it ugly compared to all these elegant solutions:

#my_list=[0,2,3,5,1]
my_list=['0','2','3','5','1']
my_list= [int(x) for x in my_list] 

new_list=[]
for i in my_list:
    for j in my_list:
        for k in range(len(my_list)):
            if i == my_list[k] and j == my_list[k-1]:
                if i == my_list[0]:
                    new_list.append(i)
                else:
                    new_list.append(i-j)

new_list= [str(x) for x in new_list] # only necessary if output should be str not int

print(new_list)

Upvotes: 2

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You can do it using a list comprehension, check if the index is 0 then leave the number as is.

Otherwise using enumerate get the current number with the index idx and the last number and subtract the two:

my_list=['0','2','3','5','1']
new_list = [ num if idx == 0 else str(int(num) - int(my_list[idx - 1])) 
             for idx, num in enumerate(my_list)]
print(new_list)

Outputs:

>> ['0', '2', '1', '2', '-4']

Upvotes: 1

yasir jafar
yasir jafar

Reputation: 187

my_list=['0','2','3','5','1']

l = [int(my_list[x+1]) - int(my_list[x]) for x in range(len(my_list)-1)]
l.insert(0,int(my_list[0]))

print(l)

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191864

In order to fix the values changing while you go, you could loop in the opposite direction of the values being updated

new_list = list(map(float, my_list))
for i in range(len(new_list), 0, -1):
     if my_list[i] != 0:
        my_list[i] -= my_list[i-1]
print(my_list) 

Upvotes: 1

Adam.Er8
Adam.Er8

Reputation: 13413

to do this with a for-loop, you can use range to go over the indexes, then calculate the element based on index and index-1, like this:

my_list=['0','2','3','5','1']

new_list = [my_list[0]]
for index in range(1, len(my_list)):
  new_list.append(str(int(my_list[index]) - int(my_list[index-1])))

print(new_list)

you can also use zip to go over the adjacent elements without dealing with indexes, like this:

my_list=['0','2','3','5','1']

new_list = [my_list[0]]
for first,second in zip(my_list, my_list[1:]):
  new_list.append(str(int(second) - int(first)))

print(new_list)

NOTE: you could get rid of the str/int casts if your lists were of type int.

Upvotes: 1

Related Questions