I have two-dimensional list:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
My desired output is:
new_list=[["hello", "my", "world"], ["my", "your", "ours"]]
I have two-dimensional list:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
My desired output is:
new_list=[["hello", "my", "world"], ["my", "your", "ours"]]
You can do it with a list comprehension which contains, as its elements, another list comprehension. At the root of it all is a call to str.lower()
to create new lower-casified strings.
Aside: it is better not to name your variables after built-in types. Try my_list=
, lst=
, or some descriptive name like mixed_case_words=
, instead of list=
new_list = [ [ item.lower() for item in sublist ] for sublist in old_list]
If you prefer loops, you can do it with nested for
loops:
new_list = []
for sublist in old_list:
new_sublist = []
for item in sublist:
new_sublist.append(item.lower())
new_list.append(new_sublist)
You may try this:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
new_list = [ [ i.lower() for i in innerlist ] for innerlist in list]
print(new_list)
Output:
[['hello', 'my', 'world'], ['my', 'your', 'ours']]
Nested list comprehension will do for your case
lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
new_lst = [ [i.lower() for i in j] for j in lst]
# [["hello", "my", "world"], ["my", "your", "ours"]
We can do something like below also using eval
and str
method, this shall handle any depth of nested list of string
lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
# replace eval with ast.literal_eval for safer eval
new_lst = eval(str(lst).lower())
# [["hello", "my", "world"], ["my", "your", "ours"]