[Tutor] removing items from list in for loop
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Feb 13 14:02:14 EST 2022
On Sun, 13 Feb 2022 13:45:47 -0500, Dennis Lee Bieber
<wlfraed at ix.netcom.com> declaimed the following:
>>>> alist = list(range(10))
>>>> alist
>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:2] + alist[3:]
>>>> rlist
>[0, 1, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:0] + alist[1:]
>>>> rlist
>[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:9] + alist[10:]
>>>> rlist
>[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>>>
>
> It should be trivial to create a loop that starts with the first
>position and goes to the length of the list.
If it isn't clear from the examples
[:pos] keep all items from start of list to <pos> (to be skipped)
[pos+1:] keep all items from after skipped <pos> to end
<pos> is 0 for the first item in the list
<pos> is len(list)-1 for the last item in the list
ie: for a 10-item list, <pos> is 0 to 9 (just what range(10) generates)
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list