Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists.
Examples:
Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202], [303], [404], [505]]
Approach #1 : Naive Approach
Use another list ‘res’ and a for a loop. Using split[] method of Python we extract each element from the list in the form of the list itself and append it to ‘res’. Finally, return ‘res’. One drawback of this method is that it does not work with integer list as ‘int’ object has no attribute ‘split’.
def
extractDigits[lst]:
res
=
[]
for
el
in
lst:
sub
=
el.split[
', '
]
res.append[sub]
return
[res]
lst
=
[
'alice'
,
'bob'
,
'cara'
]
print
[extractDigits[lst]]
Output:
[['alice'], ['bob'], ['cara']]
Approach
#2 : List comprehension
List comprehension is an efficient approach as it doesn’t make use of extra space. For each element ‘el’ in list, it simply appends [el] to the output list.
def
extractDigits[lst]:
return
[[el]
for
el
in
lst]
lst
=
[
'alice'
,
'bob'
,
'cara'
]
print
[extractDigits[lst]]
Output:
[['alice'], ['bob'], ['cara']]
Approach #3 :
Python map[]
The given code maps the function el:[el] for each item of the given iterable ‘lst’. Hence outputs each element as a list itself.
def
extractDigits[lst]:
return
list
[
map
[
lambda
el:[el], lst]]
lst
=
[
'alice'
,
'bob'
,
'cara'
]
print
[extractDigits[lst]]
Output:
[['alice'], ['bob'], ['cara']]
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Many times, we come over the dumped data that is found in the string format and we require it to be represented into the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks are quite common in web development. Let’s discuss certain ways in which this can be performed.
Method #1: Using split[]
and strip[]
ini_list
=
"[1, 2, 3, 4, 5]"
print
[
"initial string"
, ini_list]
print
[
type
[ini_list]]
res
=
ini_list.strip[
']['
].split[
', '
]
print
[
"final list"
, res]
print
[
type
[res]]
Output:
initial string [1, 2, 3, 4, 5] final list ['1', '2', '3', '4', '5']
Method #2: Using ast.literal_eval[]
import
ast
ini_list
=
"[1, 2, 3, 4, 5]"
print
[
"initial string"
, ini_list]
print
[
type
[ini_list]]
res
=
ast.literal_eval[ini_list]
print
[
"final list"
, res]
print
[
type
[res]]
Output:
initial string [1, 2, 3, 4, 5] final list [1, 2, 3, 4, 5]
Method #3: Using json.loads[]
import
json
ini_list
=
"[1, 2, 3, 4, 5]"
print
[
"initial string"
, ini_list]
print
[
type
[ini_list]]
res
=
json.loads[ini_list]
print
[
"final list"
, res]
print
[
type
[res]]
Output:
initial string [1, 2, 3, 4, 5] final list [1, 2, 3, 4, 5]