[Tutor] problem solving with lists

marcus.luetolf at bluewin.ch marcus.luetolf at bluewin.ch
Fri Mar 18 11:12:19 EDT 2022


…many thanks for your quick replay.

When I used a for loop :

 

>lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'g'], ['b', 'c', 'h']]

>sub_lst = []

>for p in lst:

>    pair1 = lst[p][0:2]

>    pair2 = list(lst[p][0]+ lst[p][2])

>    pair3 = lst[p][1:] 

>    print('pair1:', pair1, 'pair2: ', pair2, 'pair3: ', pair3)

>    if pair1 or pair2 or pair3 not in sub_lst:

>        sub_lst.append(lst[p])

>    print(sub_lst)

 

I got a traceback:

……..

line 5, in <module>    pair1 = lst[p][0:2]

TypeError: list indices must be integers or slices, not list

 

And yes, the code above did not do what I exspected. But I don’t understand 

what you mean with


If pair 1 not empty

Or pair2 not empty

Or pair3 not in newlist

 

What is the difference between pair not beeing empty or not beeing in new_list ?

How should I define the if condition properly ?

Marcus.

 

Von: alan.gauld at yahoo.co.uk <alan.gauld at yahoo.co.uk> 
Gesendet: Freitag, 18. März 2022 15:00
An: marcus.luetolf at bluewin.ch
Cc: tutor at python.org
Betreff: Re: AW: [Tutor] problem solving with lists

 

 

 

On 18 Mar 2022 13:07, marcus.luetolf at bluewin.ch <mailto:marcus.luetolf at bluewin.ch>  wrote:



>lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'g'], ['b', 'c', 'h']] 

>n = len(lst) 
>p = 0 
>new_lst = [] 
>while n > 0: 
>    pair1 = lst[p][0:2] 
>    pair2 = list(lst[p][0]+ lst[p][2]) 
>    pair3 = lst[p][1:] 
>    print('pair1:', pair1, 'pair2: ', pair2, 'pair3: ', pair3) 
>    if pair1 or pair2 or pair3 not in new_lst

 

I suspect that's not doing what you think. Python sees it as

 

If pair 1 not empty

Or pair2 not empty

Or pair3 not in newlist

 

I don't think that's what you want. 

 

BTW why does 

 

For p in lst not work? 

It seems to be what you are effectively doing... 

 

Alan G 

>From my phone, apologies for any typing errors... 

 



More information about the Tutor mailing list