Help with this code

Peter Otten __peter__ at web.de
Mon Jan 9 08:46:56 EST 2017


José Manuel Suárez Sierra wrote:

> Hello, 

Welcome!


> I am trying to make a code wich compares between 2 or several
> sequences (lists). It compares every element in a list with another list
> elements. For example, if we have a list_a=["a","b","c","d"] and
> list_b=["a","b"] I want to obtain a new list_c containing elements that
> match between these lists (a and b here), but, if for instance list_b were
> ["a","c"] the program must not store this data because they are not in
> same order.
> 
> Said this, I wrote this code but it doesnt work:

Get into the habit of describing what "doesn't work" as precisely as you 
can. That is the first and most important step to fixing a bug. Python often 
helps you with that task by producing a "traceback", in your case something 
like

$ python tmp3.py
  File "tmp3.py", line 12
    j = j+1
    ^
IndentationError: unexpected indent

probably with another filename and line number. This is the compiler trying 
to tell you that line 12 has more leading whitespace than the preceding one, 
something that should only occur e. g. for the body of a while-loop, not at 
random places like the

j = j+1

that follows the ordinary statement

c1.append(a[i])

Note that once you have fixed your code in this place you will run into 
another error. Read the traceback carefully and try to figure out what's 
going on. If you need help come back here or, better, ask on the tutor 
mailing list which is dedicated to newbies making their first steps with 
Python. Good luck!

> if __name__ == "__main__":
> 
> 
>     def compare(a, b):
> 
>         i = 0
>         j = 0
>         c1 = []
> 
>         while a[i] == b[j]:
>             c1.append(a[i])
>                 j = j+1
>                 i=i+1
> 
>         return c1
> 
> 
> 
> 
>     cadena_1=raw_input("Introduce list 1 \n")
>     cadena_2 = raw_input("Introduce list 2 \n")
> 
> 
>     transf1=list(cad_1)
>     transf2 = list(cad_2)
> 
> 
>     print compare(transf1,transf2)
> 
> 
> 
> 
> Thank you




More information about the Python-list mailing list