Python Forum

Full Version: Capitalize first letter of names in nested loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

I got this:

names=[['peter','jack','bo'],'eva',['christian','joanne',7],'5']
#Make all names in nested loop above with capital first letters, dont make new list but change current list
#elements 7 and '5' should be left as is

I can't seem to figure out how to extract these names and make it the words capital letters.

I currently am thinking of looping through the names and trying to use names.capitalize()
but can't do that on lists and all the names on the list are not capitalized as the ones in the nested lists are untouched.

Any ideas on what to do with this silly challenge?
what have you tried so far?
show code
for list in names:
    for name in list:
        name.title()
        print(name)
I am really lost as to how I can loop through all the lists and change it.
(Oct-25-2019, 10:09 AM)Larz60+ Wrote: [ -> ]what have you tried so far?
show code

Wrote it down in replies, sorry
change line 3 from
name.title()
To
name = name.title()
(Oct-25-2019, 03:11 PM)Larz60+ Wrote: [ -> ]change line 3 from
name.title()
To
name = name.title()

names=[['peter','jack','bo'],'eva',['christian','joanne',7],'5']
#Make all names in nested loop above with capital first letters, dont make new list but change current list
#elements 7 and '5' should be left as is

for list in names:
    for name in list:
        name = name.title()
        print(name)

print(names)
that does seem to make all but "eva" capital letters and prints: AttributeError: 'int' object has no attribute 'title'

which is probably as the list includes 7

furthermore, I cant print the list afterward. I don't think this for loop actually changes values within the names list?
first, you cannot name a variable 'list' as it is a reserved for a python sequence.
next you need to properly index nested lists
then check type for string
and capitalize if so
Seems like a job for recursion. What I would do is define a function that tests the type of the argument. If the argument is a list, it calls itself repeatedly on the items in the list. If the type is a string it capitalizes it and prints. If it is an int it just prints. Call it on your source list and it works.
(Oct-27-2019, 01:00 AM)jefsummers Wrote: [ -> ]Seems like a job for recursion.

That was my idea as well. However, if you need to change the list in place, note that you need to assign the capitalized string back to the list itself (specifically the index of the uncapitalized string). So it's a loop that recurses on lists, does item assignment to capitalize strings, and ignores everything else.
I also thought about recursion, but since a homework assignment, thought perhaps not allowed.