1

I have a list of integers a and I want to iterate through every element of it, and if the element is smaller or the same size as the next element in the list (the upcoming index-neighbour), I want to convert the element into a string and concatenate "000" onto it. But if it's larger than the next element, I want to concatenate "111" onto it.

I use Python 3.7.3.

Here's what I've already tried:

a = [41433, 23947, 10128, 89128, 29523, 47106]

for I in a:
      if a[I] <= a[I+1]:
             a[I] = str(a[I] + "000")
      else:
             a[I] = str(a[I] + "111")

I've actuallly tried a lot more than that, but nothing worked. When I run the code, I always get "IndexError: list index out of range".

I'm quite new in Python, anyone know a solution?

3
  • Given your description, all elements but the last one are converted to strings. Correct? So, for i in range(len(a)-1): a[i] = str(a[i]) + ('000' if a[i] <= a[i+1] else '111') Commented Jul 19, 2019 at 21:52
  • 1
    So what is your expected output, and what is the treatment for the last item in the list where it can't be compared to the one after it? Commented Jul 19, 2019 at 21:57
  • What is your expected output? Commented Jul 19, 2019 at 23:14

4 Answers 4

4

Your I value isn't an index, it's an element in a (41433, 23947 ect), so a[41433] doesn't exist.

Try using a range

for i in range(0, len(a)-1):
  if a[i] <= a[i+1]:
    a[i] = str(a[i]) + "000"
  else:
    a[i] = str(a[i]) + "111"
Sign up to request clarification or add additional context in comments.

Comments

0

I would use itertools to create two iterators for your list, and zip them together so that you get pairs of successive values:

from itertools import tee

i1, i2 = tee(a)
next(i2, None)    # advances i2 by one step
pairs = zip(i1, i2)
a = [str(elem1)+'000' 
        if elem1 <= elem2 else str(elem1)+'111' 
        for elem1, elem2 in pairs]

Comments

0

enumerate is perfect for this use case. it will also increase readability:

a = [41433, 23947, 10128, 89128, 29523, 47106]                  

for index, elem in enumerate(a[:-1]):                           
    if a[index] <= a[index+1]:                                  
        a[index] = str(a[index]) + "000"                     
    else:                                                       
        a[index] = str(a[index]) + "111"                     
print(a) 

['41433111', '23947111', '10128000', '89128111', '29523000', 47106]

Comments

0

A pythonic way would be to use enumerate, which generates tuples of (index, list[index).

for idx, val in enumerate(a[:-1]):
    if val <= a[idx+1]:
        a[idx] = str(a[idx]) + "000"
    else:
        a[idx] = str(a[idx]) + "111"

Notes
Loop until second-to-last item by using a[:-1] so that you don't run into index out of bounds errors.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.