Hi I am learning Python and for an assignment, I was asked to deconstruct a list and making it lower case using .lower() method. I am confused on how to change items in my list to lowercase using .lower and would like some help.
Here is my code, I was given this structure and had to fill out the missing areas:
def destructure(lst):
result=[]
for i in lst:
result.extend(i)
print(result)
???
lc=[['ONE','TWO','THREE'],['FOUR','FIVE','SIX']]
destructure(lc)
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX']
['one', 'two', 'three', 'four', 'five', 'six']
I tried using:
lower = [x.lower() for x in lst]
print(lower)
But this wouldn't work.
Remember that strings are immutable. Thus, when you call str.lower() or str.upper() you'll need to [re]assign the returned value.
It appears that you want to flatten the list (of lists) and produce both upper- and lower-case versions.
You could do this:
def destructure(lst, func):
rv = []
for e in lst:
rv.extend([func(s) for s in e])
return rv
lc = [['ONE','TWO','THREE'],['FOUR','FIVE','SIX']]
print(destructure(lc, str.upper))
print(destructure(lc, str.lower))
Output:
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX']
['one', 'two', 'three', 'four', 'five', 'six']