0

I have a list (in a dataframe) that looks like this:

oddnum = [1, 3, 5, 7, 9, 11, 23]

I want to create a new list that looks like this:

newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]
  1. I want to test if the distance between two numbers is 2 (if oddnum[index+1]-oddnum[index] == 2)

  2. If the distance is 2, then I want to add the number following oddnum[index] and create a new list (oddnum[index] + 1)

  3. If the distance is greater than two, keep the list as is

I keep getting key error because (I think) the list runs out of [index] and [index+1] no longer exists once it reaches the end of the list. How do I do this?

2 Answers 2

1

To pass errors, the best method is to use try and except conditions. Here's my code:

oddnum = [1, 3, 5, 7, 9, 11, 23]
res = [] # The new list
for i in range(len(oddnum)):
    res.append(oddnum[i]) # Append the first value by default
    try: # Tries to run the code
        if oddnum[i] +  2 == oddnum[i+1]: res.append(oddnum[i]+1) # Appends if the condition is met
    except: pass # Passes on exception (in our case KeyError)
print(res)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Is it possible to apply the same logic if I have two lists? For example: list1 = [5, 7, 9, 11, 17] list2 = [7, 9, 11, 13, 21] (assuming that values in list 2 are always greater than values in list 1) fill in between two values in each list (list2[index]-list1[index]) new_list = [5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 18, 19, 20, 21]
Two lists as in? Could you show an example?
I think this is what I was looking for: stackoverflow.com/questions/54960867/…
Oh, I thought you just want for one list as written. np
1
oddnum = [1, 3, 5, 7, 9, 11, 23]

new_list = []

for pos, num in enumerate(oddnum):

    new_list.append(num)
    
    try:

        if num-oddnum[pos+1] in [2, -2]:

            new_list.append(num+1)
    except:

     pass
        
print(new_list)

Use try: except: to prevent exceptions popping up and ignore it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.