Jelena Cvijan Jelena Cvijan - 2 years ago 52
Python Question

Connecting last and first value of list

I have a list of numbers, say

list= [0,1,0,1,0]
. I have to check for each element i in list whether its equal to its previous and the element after it and if it is, change its value to the previous one. I presented this task as:



for i in list:

if x=y and i!=x


elif x!=y


But I need to connect the first and the last element in list, so that if
). My idea was to define another loop like this:

if i=list[0]


But when i execute the program it writes that
is "syntax error: invalid syntax". First, I am not quite sure why is this: I was thinking that I didn't define x (but I did!), or I maybe didn't define it in the right place (I am not sure where I should define it then). On the other hand, is this the way to connect last and first value of list?

Answer Source

Here is a code that does exactly what you asked.

test=[0,1,0,1,0]   # don't use 'list' as variable name
for j in range(len(test)):   # j=index of current
  i = (j-1) % len(test)     # i=index of previous
  k = (j+1) % len(test)     # k = index of next
  if test[i] == test[j] == test[j]:  # equal to previous and next
    test[j] = test[i]        # change to previous

The problem is that this code does nothing. If current value is equal to the preceding one (quote "whether its equal to its previous and the element after it"), the change will have no effect. For example, the condition will only be True for three consecutive equal values ...7,7,7,...; so changing the current value to the previous will have no effect.

If you change your requirement to "whether it is equal to the preceding value or the one after it", change to if (test[i] == test[j]) or (test[j] == test[k]):. (The first condition still is unnecessary).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download