0

I need to write a code that Given a list of numbers return a list in which all equal adjacent elements have been reduced to a single element. example: list=[1,1,3,4,5,5,6,7,7,7,8,5,7] becomes [1,3,4,5,6,7,8,5,7]

i wrote this code:

list = []
list1 = []
for i in range(10):
  c = input("inserisci un numero: ")
  list.append(c)
k = 0
for i in range(len(list)-1):
  
  if  list[i+1] != list[i]:
    list1[k].append(list[i])
    k+=1

print(list1)

ut it's giving me index error could you explain me why?

  • Does this answer your question? [Python Removing Adjacent Numbers](https://stackoverflow.com/questions/44858453/python-removing-adjacent-numbers) – collapsar Apr 28 '22 at 18:11
  • don't shadow build-in functions, i.e. choose a different name for your list: `list_`, `lst`, ... because `list` has a special meaning, [doc](https://docs.python.org/3/library/functions.html#func-list). [and that's why has a different highlighting scheme] – cards Apr 28 '22 at 18:26

3 Answers3

2

You want list1.append(list[i]), not list1[k]. The k variable is useless.

The reason it explodes is that, the first time through the second loop, you refer to list1[0], but list1 is empty. It has no elements, so index 0 is out of bounds.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

Add the first element to result list

result.append(list[0])

then just loop from 1 to the end of the original list.

On each iteration just check if list[i-1] != list[i]: if true add to result list like this result.append(list[i])

ramkrishs
  • 78
  • 7
0

Using itertools.groupby function from the standard library you can group similar terms.

import itertools as it
l = [1,1,3,4,5,5,6,7,7,7,8,5,7]

ll = []
_ = [ll.append(next(grp)) if check else ll.append(grp) for check, grp in it.groupby(l)]
print(ll)
cards
  • 3,936
  • 1
  • 7
  • 25