Home > Back-end >  Creating lists inside a list in Python
Creating lists inside a list in Python

Time:10-23

values = ['random word1', 20, 'random word2', 54…]

The list has a string then a value and again a string then afterwards a value. The amount of strings followed by values is random. The words are random and the values are random as well

I want to convert the list to something like this:

values = [['random word1', 20], ['random word2', 54]…]

CodePudding user response:

values = ['random word1', 20, 'random word2', 54]
values = [values[i:i 2] for i in range(0,len(values),2)]
print(values)

CodePudding user response:

Try this:

values = ['random word1', 20, 'random word2', 54]
print([list(x) for x in zip(values[::2], values[1::2])])

CodePudding user response:

You can do it with zip and list slicing.

list(map(list,zip(values[::2], values[1::2])))
# [['random word1', 20], ['random word2', 54]]

CodePudding user response:

b = [[values[i], values[i 1]] for i in range(len(values)) if i%2==0]
  • Related