[Tutor] Break element into list while iterating

Alan Gauld learn2program at gmail.com
Sun Dec 26 13:33:14 EST 2021


On 25/12/2021 17:11, Julius Hamilton wrote:
> Hey,
>
> I would like to do some kind of list comprehension where elements meeting
> certain conditions get split on a delimiter. They don’t become lists nested
> in one element in the previous list; the new elements just get inserted
> where the old one was.


Not a LC as such but I did get this:


>>> L = ['apple', 'pear', 'grape']
>>> def splitInListAt(L,idx):
    return L[:idx] + [n for n in L[idx]] + L[idx+1:]

>>> splitInListAt(L,0)
['a', 'p', 'p', 'l', 'e', 'pear', 'grape']
>>> splitInListAt(L,1)
['apple', 'p', 'e', 'a', 'r', 'grape']
>>> splitInListAt(L,2)
['apple', 'pear', 'g', 'r', 'a', 'p', 'e']
>>>

Which is generic to any kind of sequence not just strings:

>>> L = [[1,2,3],(4,5,6),{7,8,9}]
>>> splitInListAt(L,0)
[1, 2, 3, (4, 5, 6), {8, 9, 7}]
>>> splitInListAt(L,1)
[[1, 2, 3], 4, 5, 6, {8, 9, 7}]
>>> splitInListAt(L,2)
[[1, 2, 3], (4, 5, 6), 8, 9, 7]
>>>

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list