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

Time:02-18

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:

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

but gives this:

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

No external libraries please.

CodePudding user response:

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.

CodePudding user response:

Try this:

a = ['foo','bar','cat','dog']
b = [x for x in zip(a, a[1:])]
  • Related