1

I am trying to convert the elements of a list of list of lowercase. This is what is looks like.

print(dataset)
[['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]

I have tried doing this:

for line in dataset:
    rt=[w.lower() for w in line]

However this gives me an error saying list object has no attribute lower().

Jasper
  • 3,939
  • 1
  • 18
  • 35
minks
  • 2,859
  • 4
  • 21
  • 29

3 Answers3

12

You have a nested structure. Either unwrap (if there is just one list contained, ever) or use a nested list comprehension:

[[w.lower() for w in line] for line in dataset]

The nested list comprehension handles each list in the dataset list separately.

If you have just one list contained in dataset, you may as well unwrap:

[w.lower() for w in dataset[0]]

This produces a list with the lowercased strings directly contained, without further nesting.

Demo:

>>> dataset = [['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
>>> [[w.lower() for w in line] for line in dataset]
[['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
>>> [w.lower() for w in dataset[0]]
['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Can't you shorten the inner loop to `map(str.lower,line)`? – Falko Feb 21 '16 at 19:28
  • 2
    @Falko: in Python 2, yes. In Python 3, you'd have to add `list()` to that. I prefer a list comprehension here, anyway, I find it more readable. The list comprehension would also support a mix of `str` and `unicode` objects out of the box. – Martijn Pieters Feb 21 '16 at 19:32
2

Either use map

map(str.lower,line)

Or list comprehension (which is basically syntactic sugar)

[x.lower() for x in line]

And this process can be nested for the entire dataset

[[x.lower() for x in line] for line in dataset]

And if you want to join all lines into one, use reduce:

reduce(list.__add__,[[x.lower() for x in line] for line in dataset])
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
0

If you wish to convert all the Strings in your list in Python, you can simply use following code:

[w.lower() for w in My_List]

My_List is your list name

Qiu
  • 5,651
  • 10
  • 49
  • 56
Mr_Null_Byte
  • 39
  • 1
  • 6