Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a sublist from a list. First with second, second with third, etc

From this

a = ['foo','bar','cat','dog']

to create another variable b that will have it as follows:

b = [['foo','bar'],['bar','cat'],['cat','dog']] # with this order

I have tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b = [[i] * 2 for i in a]

but gives this:

[['foo', 'foo'], ['bar', 'bar'], ['cat', 'cat'], ['dog', 'dog']]

No external libraries please.

>Solution :

You can use a list comprehension like you attempted to, you just need a slight modification to account for different spots in the list:

b = [[a[i-1], a[i]] for i in range(1, len(a))]

Output:

[['foo', 'bar'], ['bar', 'cat'], ['cat', 'dog']]

Since you want to pair "touching" items the a[i-1] and a[i] accomplish this. Then just loop through each i in len(a). We use range(1,len(a)) instead of range(len(a)), however, because we don’t want to pair the first value of a with something before it because it is the first value.

An arguably cleaner solution would be to use zip, but it depends on preference:

b = [list(i) for i in zip(a, a[1:])]

In this case we use a[1:] in order to offset that list so that the pairs are correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading