2
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]…]
0

4 Answers 4

2
values = ['random word1', 20, 'random word2', 54]
values = [values[i:i+2] for i in range(0,len(values),2)]
print(values)
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this method as well it works. Thanks.
2

Try this:

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

1 Comment

I have tried this method as well it works. Thanks.
0

You can do it with zip and list slicing.

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

4 Comments

list(map(list,zip( ... I suppose it's too much for the beginning beginner to understand what will be going on without a page or two of explanations ...
I have tried this method as well it works. I will choose this one as best because there is no for loop involved. I guess if the list had thousands of strings and values this would run faster than the other answers correct?
@ETHERC20, I think this method does for loops. Functions like map() and zip() create an iterator, so you need to do a for loop if you want to process all the elements, this is what list() function does.
@Mayo in this case what would you suggest? If the list had tens of thousands of strings and values it will run slow correct? How can I make it better?
-2
b = [[values[i], values[i+1]] for i in range(len(values)) if i%2==0]

2 Comments

First think, than write code and finally test the code before posting anything here on stackoverflow.
It's actually what' i've done, but with a very specific (and wrong) test case. There is no need to be rude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.