I'm new in Python and I was trying to change the case in a list of lists with mixed elements. I would like to change the fourth element in every sublist with title function The list is something like this:
records = [2011, 'FEMALE', 'HISPANIC', 'SOPHIA', 223, 3],
[2011, 'FEMALE', 'HISPANIC', 'SOPHIE', 12, 76],
[2011, 'FEMALE', 'HISPANIC', 'STACY', 10, 78],
[2011, 'FEMALE', 'HISPANIC', 'STELLA', 11, 77],
.......
The result I would like to get is something like this:
records = [2011, 'FEMALE', 'HISPANIC', 'Sophia', 223, 3],
[2011, 'FEMALE', 'HISPANIC', 'Sophie', 12, 76],
[2011, 'FEMALE', 'HISPANIC', 'Stacy', 10, 78],
[2011, 'FEMALE', 'HISPANIC', 'Stella', 11, 77],
.......
I was trying to do this:
`for row in range(records):`
`row[3].title()`
but I get the following error:
TypeError: 'list' object cannot be interpreted as an integer
I would be grateful If someone could help me.
You were almost there!
Considering the input as:
records = [[2011, 'FEMALE', 'HISPANIC', 'SOPHIA', 223, 3],
[2011, 'FEMALE', 'HISPANIC', 'SOPHIE', 12, 76],
[2011, 'FEMALE', 'HISPANIC', 'STACY', 10, 78],
[2011, 'FEMALE', 'HISPANIC', 'STELLA', 11, 77]]
You can iterate over the main list this way:
for row in records:
row[3] = row[3].title()
Or, alternatively, you can index the for loop:
for i in range(len(records)):
records[i][3] = records[i][3].title()
Both produces the following result:
[[2011, 'FEMALE', 'HISPANIC', 'Sophia', 223, 3],
[2011, 'FEMALE', 'HISPANIC', 'Sophie', 12, 76],
[2011, 'FEMALE', 'HISPANIC', 'Stacy', 10, 78],
[2011, 'FEMALE', 'HISPANIC', 'Stella', 11, 77]]