-4

So, i'm trying to make my elements in my lists uppercase, but i can't make the standard something.upper(), i'm guessing because of the lists in the lists. fx:

names = [['henry', 'mike'],'jones', 'kevin',['michael', 'simon']]

How do i do this?

Thank you

  • 4
    please make an attempt before asking and provide a [mcve] – depperm Oct 22 '18 at 16:35
  • 1
    That's *really* not a two-dimensional list; it's just a list that has other lists as some of its elements. A "real" two-dimensional list would at least have a list as *each* of its elements. – chepner Oct 22 '18 at 16:39
  • `names[0][0].upper()`. Of course it's up to you to know whether you're inside a sublist. – John Gordon Oct 22 '18 at 16:41

3 Answers3

2

Check if the element is of type string of list

for i in names:
    if isinstance(i,list):
        for inner_element in i:
            print(inner_element.upper())
    elif isinstance(i,str): # to handle the case if ints are also present
        print(i.upper())

If you want to replace the values in existing list

for index,i in enumerate(names):
    if isinstance(i,list):
        temp=[]
        for inner_element in i:
            temp.append(inner_element.upper())
        names[index]=temp
    elif isinstance(i,str):
        names[index]=i.upper()
mad_
  • 8,121
  • 2
  • 25
  • 40
0

You can use list comprehensions as follows:

uppercase_names = [ name.upper() if isinstance(name, str) else [n.upper() for n in name if isinstance(n, str)] for name in names ]

Basically, we're using isinstance(name, str) to check if the object is actually a string object.

In case there are integers in the list, you can use this complex comprehension:

uppercase_names = [ name.upper() if isinstance(name, str) else name if isinstance(name, int) else [ n.upper() if isinstance(n, str) else n if isinstance(n, int) else n for n in name ] for name in names ]
rockikz
  • 586
  • 1
  • 6
  • 17
0

You could try this if the depth of the list is not known upfront.

Input:

names=['jones', 'kevin', ['henry', 37, ['a', 0.69999]], ['michael', True]]

Function:

def recursive_upper(names):
 ret_list=[]
 for x in names:
     if isinstance(x, list):
         ret_list.append(recursive_upper(x))
     elif (isinstance(x, basestring) or isinstance(x, int) or isinstance(x, float) \
           or isinstance(x, long) or isinstance(x, bool) or isinstance(x, complex)):
         ret_list.append(str(x).upper())
 return ret_list

print recursive_func(names)

Output:

['JONES', 'KEVIN', ['HENRY', '37', ['A', '0.69999']], ['MICHAEL', 'TRUE']]

The function simply checks the type and recursively calls itself if type is a list. It continues to return the uppercase version of text when it finds a string, int, float, long, bool or a complex type. All other types are simply ignored. (You could add/delete types in the elif condition. Refer here )

Hope this helps :)

ABShankar
  • 1
  • 2