Ошибка list object has no attribute lower

In Python, the list data structure stores elements in sequential order. We can use the String lower() method to get a string with all lowercase characters. However, we cannot apply the lower() function to a list. If you try to use the lower() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘lower’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


Table of contents

  • AttributeError: ‘list’ object has no attribute ‘lower’
    • Python lower() Syntax
  • Example
    • Solution
  • Summary

AttributeError: ‘list’ object has no attribute ‘lower’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘lower’” tells us that the list object we are handling does not have the lower attribute. We will raise this error if we try to call the lower() method on a list object. lower() is a string method that returns a string with all lowercase characters.

Python lower() Syntax

The syntax for the String method lower() is as follows:

string.lower()

The lower() method ignores symbols and numbers.

Let’s look at an example of calling the lower() method on a string:

a_str = "pYTHoN"

a_str = a_str.lower()

print(a_str)
python

Next, we will see what happens if we try to call lower() on a list:

a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"]

a_list = a_list.lower()

print(a_list)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"]
      2 
----≻ 3 a_list = a_list.lower()
      4 
      5 print(a_list)

AttributeError: 'list' object has no attribute 'lower'

The Python interpreter throws the Attribute error because the list object does not have lower() as an attribute.

Example

Let’s look at an example where we read a text file and attempt to convert each line of text to all lowercase characters. First, we will define the text file, which will contain a list of phrases:

CLiMBinG iS Fun 
RuNNing is EXCitinG
SwimmING iS RElaXiNg

We will save the text file under phrases.txt. Next, we will read the file and apply lower() to the data:

data = [line.strip() for line in open("phrases.txt", "r")]

print(data)

text = [[word for word in data.lower().split()] for word in data]

print(text)

The first line creates a list where each item is a line from the phrases.txt file. The second line uses a list comprehension to convert the strings to lowercase. Let’s run the code to see what happens:

['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg']
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 data = [line.strip() for line in open("phrases.txt", "r")]
      2 print(data)
----≻ 3 text = [[word for word in data.lower().split()] for word in data]
      4 print(text)

AttributeError: 'list' object has no attribute 'lower'

The error occurs because we applied lower() to data which is a list. We can only call lower() on string type objects.

Solution

To solve this error, we can use a nested list comprehension, which is a list comprehension within a list comprehension. Let’s look at the revised code:

data = [line.strip() for line in open("phrases.txt", "r")]

print(data)

text = [[word.lower() for word in phrase.split()] for phrases in data]

print(text)

The nested list comprehension iterates over every phrase, splits it into words using split(), and calls the lower() method on each word. The result is a nested list where each item is a list that contains the lowercase words of each phrase. Let’s run the code to see the final result:

['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg']
[['climbing', 'is', 'fun'], ['running', 'is', 'exciting'], ['swimming', 'is', 'relaxing']]

If you want to flatten the list you can use the sum() function as follows:

flat_text = sum(text, [])

print(flat_text)
['climbing', 'is', 'fun', 'running', 'is', 'exciting', 'swimming', 'is', 'relaxing']

There are other ways to flatten a list of lists that you can learn about in the article: How to Flatten a List of Lists in Python.

If we had a text file, where each line is a single word we would not need to use a nested list comprehension to get all-lowercase text. The file to use, words.txt contains:

CLiMBinG
RuNNing
SwimmING

The code to use is as follows:

text = [word.lower() for word in open('words.txt', 'r')]

print(text)

Let’s run the code to see the output:

['climbing', 'running', 'swimming']

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘lower’” occurs when you try to use the lower() function to replace a string with another string on a list of strings.

The lower() function is suitable for string type objects. If you want to use the lower() method, ensure that you iterate over the items in the list of strings and call the lower method on each item. You can use list comprehension to access the items in the list.

Generally, check the type of object you are using before you call the lower() method.

For further reading on AttributeErrors involving the list object, go to the articles:

How to Solve Python AttributeError: ‘list’ object has no attribute ‘split’.

How to Solve Python AttributeError: ‘list’ object has no attribute ‘shape’.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

I am new to Python and to Stackoverflow(please be gentle) and am trying to learn how to do a sentiment analysis. I am using a combination of code I found in a tutorial and here: Python — AttributeError: ‘list’ object has no attribute However, I keep getting

Traceback (most recent call last):
    File "C:/Python27/training", line 111, in <module>
    processedTestTweet = processTweet(row)
  File "C:/Python27/training", line 19, in processTweet
    tweet = tweet.lower()
AttributeError: 'list' object has no attribute 'lower'`

This is my code:

import csv
#import regex
import re
import pprint
import nltk.classify


#start replaceTwoOrMore
def replaceTwoOrMore(s):
    #look for 2 or more repetitions of character
    pattern = re.compile(r"(.)1{1,}", re.DOTALL)
    return pattern.sub(r"11", s)

# process the tweets
def processTweet(tweet):
    #Convert to lower case
    tweet = tweet.lower()
    #Convert www.* or https?://* to URL
    tweet = re.sub('((www.[s]+)|(https?://[^s]+))','URL',tweet)
    #Convert @username to AT_USER
    tweet = re.sub('@[^s]+','AT_USER',tweet)
    #Remove additional white spaces
    tweet = re.sub('[s]+', ' ', tweet)
    #Replace #word with word
    tweet = re.sub(r'#([^s]+)', r'1', tweet)
    #trim
    tweet = tweet.strip(''"')
    return tweet

#start getStopWordList
def getStopWordList(stopWordListFileName):
    #read the stopwords file and build a list
    stopWords = []
    stopWords.append('AT_USER')
    stopWords.append('URL')

    fp = open(stopWordListFileName, 'r')
    line = fp.readline()
    while line:
        word = line.strip()
        stopWords.append(word)
        line = fp.readline()
    fp.close()
    return stopWords

def getFeatureVector(tweet, stopWords):
    featureVector = []
    words = tweet.split()
    for w in words:
        #replace two or more with two occurrences
        w = replaceTwoOrMore(w)
        #strip punctuation
        w = w.strip(''"?,.')
        #check if it consists of only words
        val = re.search(r"^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$", w)
        #ignore if it is a stopWord
        if(w in stopWords or val is None):
            continue
        else:
            featureVector.append(w.lower())
     return featureVector

def extract_features(tweet):
    tweet_words = set(tweet)
    features = {}
    for word in featureList:
        features['contains(%s)' % word] = (word in tweet_words)
    return features


#Read the tweets one by one and process it
inpTweets = csv.reader(open('C:/GsTraining.csv', 'rb'),
                       delimiter=',',
                       quotechar='|')
stopWords = getStopWordList('C:/stop.txt')
count = 0;
featureList = []
tweets = []

for row in inpTweets:
    sentiment = row[0]
    tweet = row[1]
    processedTweet = processTweet(tweet)
    featureVector = getFeatureVector(processedTweet, stopWords)
    featureList.extend(featureVector)
    tweets.append((featureVector, sentiment))

# Remove featureList duplicates
featureList = list(set(featureList))

# Generate the training set
training_set = nltk.classify.util.apply_features(extract_features, tweets)

# Train the Naive Bayes classifier
NBClassifier = nltk.NaiveBayesClassifier.train(training_set)

# Test the classifier
with open('C:/CleanedNewGSMain.txt', 'r') as csvinput:
    with open('GSnewmain.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput, lineterminator='n')
    reader = csv.reader(csvinput)

    all=[]
    row = next(reader)

    for row in reader:
        processedTestTweet = processTweet(row)
        sentiment = NBClassifier.classify(
            extract_features(getFeatureVector(processedTestTweet, stopWords)))
        row.append(sentiment)
        processTweet(row[1])

    writer.writerows(all)

Any help would be massively appreciated.

In this tutorial, we will discuss on how to solve the attributeerror: ‘list’ object has no attribute ‘lower’ and explain the solutions through step-by-step method.

Before we proceed to the next discussion, we will know first if what is ‘list’ object has no attribute ‘lower’.

The “List object has no attribute ‘lower‘” is a Python error message shows that you are trying to call the string method lower() on a list object.

However, lists doesn’t have a “lower” method because it is only applies to strings function.

Why you getting this error list object has no attribute lower?

You getting this error list object has no attribute lower because you are trying to use the “lower” method on a list object in Python.

However, the “lower” method is used to convert all the characters in a string to lowercase.

What are the common causes of this error?

The “AttributeError: ‘list’ object has no attribute ‘lower’” error usually occurs if you try to use the “lower()” method on a list object in Python.

This error typically occurs due to some multiple reasons:

  • Calling the lower() method on a list:
    • If you are trying to call this method on a list object, you will get the AttributeError because lists doesn”t have the lower() method.
  • Assigning a list to a variable that previously held a string:
    • If you are assigning a list object to a variable that previously retained a string, and then you are trying to call the lower() method on that variable, you will get the AttributeError because the variable now refers to a list object, not a string.
  • Passing a list object to a function that expects a string:
    • If you are passing a list object to a function that you assume a string as an argument, and that function tries to call the lower() method on the argument, you will get the AttributeError because the function is trying to call a string method on a list object.

Here is an example on how you could get the “AttributeError: ‘list’ object has no attribute ‘lower’” error in Python:

my_list = ["apple", "banana", "cherry"]
my_list.lower()

In this example code, we have a list object called “my_list” that consist of three strings.

However, we are trying to call the lower() method on the list object, that will result in the AttributeError because lists doesn’t have the lower() method.

If we run the code example we will get this error message look likes below:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 2, in
my_list.lower()
AttributeError: ‘list’ object has no attribute ‘lower’

How to solve the attributeerror: ‘list’ object has no attribute ‘lower’?

The most better solutions To solve the attributeerror: ‘list’ object has no attribute ‘lower’ by using the lower() function on the strings on the list.

For example, we should call the lower() method on each string in the list by using a for loop.

Let’s take a look the example below:

my_list = ["APPLE", "BANANA", "CHERRY"]
for item in my_list:
    print(item.lower())

In this updated example, we are looping through each string in the list and calling the lower() method on each string individually, which will give us the desired output of the strings in lowercase letters.

If we run the code example it will show an output and there is no error anymore:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
apple
banana
cherry

Note: You should remember always that you need test your code thoroughly and you can use the best practices when working with lists and other data types in Python.

FAQs

Why do lists not have a lower() method in Python?

Lists are a type of collection in Python that store multiple values. Unlike strings, lists doesn’ have a fixed length and can consist elements of different data types.

Since the lower() method is specific to strings and it does not applicable to other data types, so it is not available for lists.

What are some other common errors that occur when working with lists in Python?

Some common errors that occur when working with lists in Python include IndexError, TypeError and ValueError.

Conclusion

To conclude, In this tutorial, we’ve shown you how to solve the AttributeError: ‘list’ object has no attribute ‘lower’ error in Python. Whether you can choose to convert the list to a string.

Also, you can use a loop to iterate through the list.

You can also, check if the object is a list before calling the method, the most important thing is that you understand the cause of the error and how to solve it.

While there are times when you will inevitably mistake function calls on data types for which it is not allowed, that is also the cause of the error AttributeError: ‘list’ object has no attribute ‘lower’. The following article will help you find a solution to this error. Hope you will read the whole article.

The error happens because you call lower() on a list instead of you calling it on a string.

The lower() function syntax:

str.lower()

The str.lower() function returns a string that converts all uppercase to lowercase.

Example

uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE']

# Call the lower() method on the list
print(uppercaseList.lower())

Output:

Traceback (most recent call last):
 File "./prog.py", line 4, in <module>
AttributeError: 'list' object has no attribute 'lower'

How to solve the AttributeError: ‘list’ object has no attribute ‘lower’?

Convert the list to a string.

If you have a list that you want to use the lower() function on, convert the list to a string first.

Example:

  • Convert the list to a string using the join() function.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE']

# Use the join() function to convert a list to a string
listConvertToStr = ' '.join(uppercaseList)
print(listConvertToStr)
print(type(listConvertToStr))

# The lower() function converts uppercase letters to lowercase letters
print(listConvertToStr.lower())

Output:

VISIT LEARNSHAREIT WEBSITE
<class 'str'>
visit learnshareit website

Access the list index and then use the lower() function.

Example:

  • You can use the index to access each element in the list and then call lower() on each of those elements.
  • Note: The list index starts from 0 and ends with the length of the list – 1.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE']

# Access the index and call lower() on the indexes
print(uppercaseList[0].lower())
print(uppercaseList[1].lower())
print(uppercaseList[2].lower())

Output:

visit
learnshareit
website

Use list comprehension or for loop.

Using list comprehension or for loop are also good ideas to fix the error.

Example:

uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE']

# Use list comprehension and lower() function
lowerList = [i.lower() for i in uppercaseList]
print(lowerList)

Output:

['visit', 'learnshareit', 'website']

Or use for loop.

Example:

uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE']

# Use for loop and lower() function
for i in uppercaseList:
    lowerList = i.lower()
    print(lowerList)

Output:

visit
learnshareit
website

Summary

Through this article, you have an idea to fix the AttributeError: ‘list’ object has no attribute ‘lower’ in Python. Use the list comprehension or for loop so you don’t have to convert the list to a string. Leave a comment so I can know how you feel about the article. Thanks for reading!

Maybe you are interested:

  • AttributeError: ‘list’ object has no attribute ‘len’
  • AttributeError: ‘list’ object has no attribute ‘find’
  • AttributeError: ‘list’ object has no attribute ‘encode’

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

AttributeError: list object has no attribute lower error’s root cause is invoking/ accessing lower() attribute from list object although lower() is not defined list class. The lower() attributes belong to str type object/class. This basically converts the string into lowercase. Sometimes we need to convert the elements of a list into lowercase we directly invoke it with list object. Which ultimately throws this AttributeError. , In this article, we will explore the best ways to fix this attributeerror.

list object has no attribute lower

list object has no attribute lower

Firstly, let’s replicate the issue with some examples and then we will take the same example to explain the fix for this error.

AttributeError list object has no attribute lower root cause

AttributeError list object has no attribute lower root cause

Solution 1: Accessing the element as str –

Suppose your intent is to convert a particular element of the list into lowercase str. But Somehow you applied the lower() function in the complete list. Now the interpreter is throwing this list Attributeerror. Now we can fix up this error by accessing individual elements as str objects and then applying the lower function.

sample_list=['A','B','C']
sample_lower=sample_list[0].lower()
print(sample_lower)

list object has no attribute lower fix by accessing element

list object has no attribute lower fix by accessing element

Solution 2: Accessing full list as str via loop –

Suppose you want to convert the full list of elements into lowercase. Now as we have already observed if we apply the lower() function directly to the list. It will be through the attributeerror. So we will iterate the list via some loop and access each element as str object then convert it into lowercase. Since the idea was to convert the complete list into lowercase hence we will append it back into a different list altogether. Here in the below code, the sample_lower is the final list.

sample_list=['A','B','C']
sample_lower=[]
for i in range(len(sample_list)):
 sample_lower.append(sample_list[i].lower())
print(sample_lower)

list object has no attribute lower fix by accessing complete list

list object has no attribute lower fix by accessing complete list

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Понравилась статья? Поделить с друзьями:
  • Ошибка l071 jcb что значит
  • Ошибка lineage 2 crash report как исправить
  • Ошибка lin на домофоне цифрал
  • Ошибка l071 jcb 531 70
  • Ошибка l03 candy стиральная машина