# Python | Convert 1D list to 2D list of variable length

Given a 1D list ‘lst’ and list of variable lengths ‘var_lst’, write a Python program to convert the given 1D list to 2D list of given variable lengths.

Examples:

```Input : lst = [1, 2, 3, 4, 5, 6]
var_lst = [1, 2, 3]
Output : [[1], [2, 3], [4, 5, 6]]

Input : lst = ['a', 'b', 'c', 'd', 'e']
var_lst = [3, 2]
Output : [['a', 'b', 'c'], ['d', 'e']]
```

Method #1 : List slicing

 `# Python3 program to Convert 1D  ` `# list to 2D list ` `from` `itertools ``import` `islice ` ` `  `def` `convert(lst, var_lst): ` `    ``idx ``=` `0` `    ``for` `var_len ``in` `var_lst: ` `        ``yield` `lst[idx : idx ``+` `var_len] ` `        ``idx ``+``=` `var_len ` `     `  `# Driver code ` `lst ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``6``] ` `var_lst ``=` `[``1``, ``2``, ``3``] ` `print``(``list``(convert(lst, var_lst))) `

Output:

```[[1], [2, 3], [4, 5, 6]]
```

Method #2 : Using itertools.islice()

 `# Python3 program to Convert 1D  ` `# list to 2D list ` `from` `itertools ``import` `islice ` ` `  `def` `convert(lst, var_lst): ` `    ``it ``=` `iter``(lst) ` `    ``return` `[``list``(islice(it, i)) ``for` `i ``in` `var_lst] ` `     `  `# Driver code ` `lst ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``6``] ` `var_lst ``=` `[``1``, ``2``, ``3``] ` `print``(convert(lst, var_lst)) `

Output:

```[[1], [2, 3], [4, 5, 6]]
```

My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.