dopewasher
dopewasher

Reputation: 3

Python - Deconstructing a list and making it lower case using .lower()

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:

Deconstructing the list

def destructure(lst):
  result=[]    
  for i in lst:
    result.extend(i)
  print(result)

Changing items to lowercase

???

Function

lc=[['ONE','TWO','THREE'],['FOUR','FIVE','SIX']]
destructure(lc)

Expected Output

['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.

Upvotes: 0

Views: 129

Answers (3)

Marcin Tamiński
Marcin Tamiński

Reputation: 11

If your input list might have any number of nested lists, then this should do it.

def destructure(lst):
    uc = [ ]
    lc = [ ]
    def destructure(lst):
        for v in lst:
            if isinstance(v, list):
                destructure(v)
            else:
                uc.append(v.upper())
                lc.append(v.lower())
    destructure(lst)
    return uc, lc
    
uc, lc = destructure(lst)
print(uc)
print(lc)

Upvotes: 0

Armaggheddon
Armaggheddon

Reputation: 348

You don't have a list you have a list of lists. Applying lower() to x is therefore being applied to a list instead than to a string and will not work, and in fact the interpreter will complain about AttributeError: 'list' object has no attribute 'lower'.
You have to iterate through all the sublists and apply the operator to each of the strings as follows:

def destructure(lst):
    low = []
    up = []
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            low.append(lst[i][j].lower())
            up.append(lst[i][j].upper())
    return (low, up)


lc=[['ONE','TWO','THREE'],['FOUR','FIVE','SIX']]
low, up = destructure(lc)

print(up)
#output = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX']

print(low)
#output = ['one', 'two', 'three', 'four', 'five', 'six']

Upvotes: -1

Adon Bilivit
Adon Bilivit

Reputation: 26825

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']

Upvotes: 1

Related Questions