Problem with rearanging list with paired letters next to each others
Bischoop
Bischoop at vimart.net
Wed Nov 11 06:45:53 EST 2020
On 2020-11-11, MRAB <python at mrabarnett.plus.com> wrote:
>>
> Points to note in your first code:
>
> 1. Modifying a list while iterating over it is a bad idea.
>
> 2. You're modifying the list that you're passing in and also returning
> it. That's a bad idea. Either modify it in place or modify and return a
> copy.
>
> 3. The line:
>
> m = (letter_list.index(x))
>
> returns the position of the first occurrence of x.
>
> Points to note in your second code:
>
> 1. (See above)
>
> 2. (See above)
>
> 3. (See above)
>
> 4. 'i' goes from 0 to len(letter_list)-1, so i+1 goes from 1 to
> len(letter_list), but the maximum index permitted by letter_list is
> len(letter_list)-1, hence letter_list[i+1] will raise IndexError on the
> last iteration.
>
> 5. 'i' goes from 0 to len(letter_list)-1, so i-1 goes from -1 to
> len(letter_list)-2. letter_list[-1] returns the last (final) letter in
> the list, and it's treated as a true.
>
> 6. This:
>
> x != letter_list[i+1] and letter_list[i-1]
>
> is checking whether:
>
> x != letter_list[i+1]
>
> is true and also whether:
>
> letter_list[i-1]
>
> is true.
I see now I overcomplicated it, what is a good idea then?
More information about the Python-list
mailing list