Reputation: 39
I have a list m:
m = ['Apple', 'Lemon', 'Orange']
and I want output as follows:
['Apple'], ['Lemon'], ['Orange']
How can this be done without using list comprehension and for cycles?
In my approach I dont understand what variables to use. Any ideas?
def lists(m):
count=0`
while count < len(m):
len(m)
count += 1
return #separated lists?
print(lists(m))
Upvotes: 0
Views: 327
Reputation: 42143
you could use recursion and parameter unpacking
def makeLists(first,*rest):
return [[first]] + (makeLists(*rest) if rest else [])
m = ['Apple', 'Lemon', 'Orange']
print(makeLists(*m))
# [['Apple'], ['Lemon'], ['Orange']]
You can also make it without parameter unpacking:
def makeLists(strings):
return ([strings[:1]] + makeLists(strings[1:])) if strings else []
m = ['Apple', 'Lemon', 'Orange']
print(makeLists(m))
# [['Apple'], ['Lemon'], ['Orange']]
Upvotes: 0
Reputation: 5520
No list comprehension, presumably no "for cycles" (might depend on what you mean), and results in a tuple
as requested.
>>> *map(lambda s: [s], m),
(['Apple'], ['Lemon'], ['Orange'])
Upvotes: 0
Reputation: 5237
Here's a traditional while
loop approach. Details of how it works are in the comments.
m = ['Apple', 'Lemon', 'Orange']
def list_to_lists(lst):
i = 0
# this will be the result list, containing lists of strings
res = []
while i < len(lst):
# [lst[i]] creates a new list containing the i'th element of lst
# res.append will append this to the result list
res.append([lst[i]])
i += 1
# return the result list
return res
lists = list_to_lists(m)
print(lists)
Its been an incredibly long time since I've actually written a while
loop. Do note that for
loops are often neater for this sort of thing - see @daniel-hao's example.
Upvotes: 0
Reputation: 4980
Since you have asked to avoid List Comprehension, you could try something like this: (BTW, while
is just kind of for
loop!)
m = ['Apple', 'Lemon', 'Orange']
from typing import List
def split_list(lst: List[str]):
res = []
for item in lst:
res.append([item])
return res
print(split_list(m))
Upvotes: 1