This question already has answers here:
l.append[i], object is not subscriptable? [closed]
(2 answers)
Closed 8 years ago.
exxy = ['mix', 'xyz', 'aardvark', 'xanadu', 'apple']
pleasework = []
ten = []
for s in exxy:
if s[0] == 'x':
pleasework.insert[0, s]
else:
ten.append[s]
pleasework.sort()
ten.sort()
pleasework.append(ten)
print pleasework
I keep getting an error that says that object is not subscriptable.
Traceback (most recent call last):
File "/Users/jerrywalker/Desktop/CompSci/Programming/Programming_Resources/Python/idle.py", line 10, in <module>
ten.append[s]
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm not really sure what this means. I've just started Python yesterday... I'm sure it's something in the code that I'm not doing right, because even when I change the name of my variables around the error is the same.
"Subscriptable" means that you're trying to access an element of the object. In the following:
ten.append[s]
you're trying to access element s of ten.append. Since you want to call it as a function/method instead, you need to use parens:
ten.append(s)
You have defined two lines with the wrong syntax:
It shouldn't be:
pleasework.insert[0, s]
ten.append[s]
But rather:
pleasework.insert(0, s)
ten.append(s)
ten.append(s) is a list method and you cannot try to get a element s of ten.append(s).
Even assuming you were trying to do something like ten[s] it would still return a error because s has to be the index (which is a integer) of the element you want
Related
I have this piece of code:
for keys in self.keys:
if has_classes := self.class_checker(keys[0]):
print(type(keys[0])) -> #just for demonstrating that it is actual list
keys[0] = [x for x in keys[0] if 'class="' not in x]
for classes in has_classes:
keys[0].append(f'class="{classes}"')
I want to change the list by using list comprehension and it is showing this error:
<class 'list'>
Traceback (most recent call last):
File "C:\Users\USER\OneDrive\Desktop\XPATH\base\main.py", line 300, in <module>
XPanther('<h1 class="Uo8X3b OhScic zsYMMe">Lidhjet e qasshmërisë</h1>', 'C:\\Users\\USER\\OneDrive\\Desktop\\XPATH\\xpath_test_case.txt').capture()
File "C:\Users\USER\OneDrive\Desktop\XPATH\base\main.py", line 100, in capture
keys[0] = [x for x in keys[0] if 'class="' not in x]
~~~~^^^
TypeError: 'tuple' object does not support item assignment
As you can see on the first line of the error, it is printing the type of keys[0] as a list (which I also know is a list but anyways), and then it suddenly becomes a tuple ?
I'm very confused, please someone help me!
As #bereal has mentioned (and others..) in the comments of my post, the actual case for this problem is that I tried to change the contents of a list,which that list happens to be inside a tuple, which is immutable in itself, so i can't change it's values at all. The obvious solution would be to first transform the tuple into a list,then back again as a tuple if you want.
This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed 1 year ago.
I was working with doubly linked lists in Python when I encountered with this error:
def merge(self,other):
mergedCenter = HealthCenter()
selfPatient = self._head
otherPatient = other._head
print(selfPatient.elem)
print(selfPatient.elem < otherPatient.elem)
while (selfPatient or otherPatient):
if selfPatient.elem < otherPatient.elem:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
elif selfPatient.elem > otherPatient.elem:
mergedCenter.addLast(otherPatient.elem)
otherPatient = otherPatient.next
else:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
otherPatient = otherPatient.next
return (mergedCenter)
I get this output:
Abad, Ana 1949 True 0
True
Traceback (most recent call last):
File "main.py", line 189, in <module>
hc3 = hc1.merge(hc2)
File "main.py", line 112, in merge
if selfPatient.elem < otherPatient.elem:
AttributeError: 'NoneType' object has no attribute 'elem'
There's already a method implemented to compare .elem as you can clearly see in the second print, but I don't understand why in the first conditional it keeps breaking.
Thanks in advance.
Solution:
Had to take into account the length of both DLists, not to get one of both values 'Nonetype'. This is solved changing the OR for AND, and checking later which one is not 'Nonetype' to finish merging
This checks if either are non-None, so if one is, and not the other, the loop is entered
while (selfPatient or otherPatient)
If you want to access both elem attributes, then both need to be non-None, requiring you to change the or to and
Otherwise, you need separate logic before the if statements to handle when only one is None, then maybe break the loop so that the return will be reached. And still wouldn't hurt to wrap the rest of the existing logic in if selfPatient and otherPatient since you're using attributes from both
As for why one becomes None, that depends on your logic for iterating the linked lists
This question already has answers here:
Python's insert returning None?
(4 answers)
Closed 5 years ago.
I'm working on a polynomial organizer. I need to insert two items into the list of coefficients and powers, (a zero for the coefficient and the missing power) wherever needed.
print poly
poly=list(poly.split(','))
for i in range(0,13):
if int(poly[i*2+1])!=int(12-i):
poly=poly.insert((i*2+1),str(12-i))
poly=poly.insert((i*2+1),"0")
returns
0,12,0,11,0,10,0,9,0,8,-7,7,1,5,-1,4,1,3,-2,2,5,0
Traceback (most recent call last):
File "python", line 105, in <module>
File "python", line 97, in mypoly
AttributeError: 'NoneType' object has no attribute 'insert'
I'm confused because from what I've read on the insert function, it is made to work on lists, but here it seems not to. Please don't kill this question... I've been trying to figure it out on my own for a while now, and always run into this problem.
So I want it to look like this:
[0,12,0,11,0,10,0,9,0,8,-7,7,0,6,1,5,-1,4,1,3,-2,2,0,1,5,0]
Notice the 0,6 and 0,1.
The method insert of list returns None, since it modifies the list. You have to change poly = poly.insert(...) to just poly.insert(...):
print poly
poly=list(poly.split(','))
for i in range(0, 13):
if int(poly[i*2+1]) != int(12-i):
poly.insert((i*2+1), str(12-i))
poly.insert((i*2+1), "0")
This question already has answers here:
How to change values in a tuple?
(17 answers)
Closed last month.
Can anyone help me with this code?
Jobs = ()
openFile = open('Jobs.txt')
x = 1
while x != 0:
Stuff = openFile.readline(x)
if Stuff != '':
Jobs.append(Stuff)
else:
x = 0
This code throws:
AttributeError: 'tuple' object has no attribute 'append'
I'm using Python 3.6.
In the line:
Jobs = ()
you create a tuple. A tuple is immutable and has no methods to add, remove or alter elements. You probably wanted to create a list (lists have an .append-method). To create a list use the square brackets instead of round ones:
Jobs = []
or use the list-"constructor":
Jobs = list()
However some suggestions for your code:
opening a file requires that you close it again. Otherwise Python will keep the file handle as long as it is running. To make it easier there is a context manager for this:
with open('Jobs.txt') as openFile:
x = 1
while x != 0:
Stuff = openFile.readline(x)
if Stuff != '':
Jobs.append(Stuff)
else:
x = 0
As soon as the context manager finishes the file will be closed automatically, even if an exception occurs.
It's used very rarely but iter accepts two arguments. If you give it two arguments, then it will call the first each iteration and stop as soon as the second argument is encountered. That seems like a perfect fit here:
with open('Jobs.txt') as openFile:
for Stuff in iter(openFile.readline, ''):
Jobs.append(Stuff)
I'm not sure if that's actually working like expected because openFile.readline keeps trailing newline characters (\n) so if you want to stop at the first empty line you need for Stuff in iter(openFile.readline, '\n'). (Could also be a windows thingy on my computer, ignore this if you don't have problems!)
This can also be done in two lines, without creating the Jobs before you start the loop:
with open('Jobs.txt') as openFile:
# you could also use "tuple" instead of "list" here.
Jobs = list(iter(openFile.readline, ''))
Besides iter with two arguments you could also use itertools.takewhile:
import itertools
with open('Jobs.txt') as openFile:
Jobs = list(itertools.takewhile(lambda x: x != '', openFile))
The lambda is a bit slow, if you need it faster you could also use ''.__ne__ or bool (the latter one works because an empty string is considered False):
import itertools
with open('Jobs.txt') as openFile:
Jobs = list(itertools.takewhile(''.__ne__, openFile))
The Jobs object you created is a tuple, which is immutable. Therefore, you cannot "append" anything to it.
Try
Jobs = []
instead, in which you create a list object.
I had also experienced the same problem. But I found the solution. For me this worked.
Problem:
w=[]
x=[],
y=[],
z=[]
for i in range(4):
w.append(i) # doesn't throw error
print(w)
This did not give error for w because I had initialized w to w = [] without comma(,) and it treated as list but when I applied the same for x it gave the error because I have initialized it as x = [], with comma here and it treated as tuple.
for i in range(4):
y.append(i) # throws error AttributeError: 'tuple' object has no attribute 'append'
print(y)
This solved for me and I have tried this in python3 in pycharm.
The curved brackets are not the correct bracket for creating lists.
Use the square brackets for lists.
This question already has answers here:
TypeError: 'list' object is not callable while trying to access a list
(9 answers)
Closed 6 years ago.
I always get the Error: 'List' object not callable... I looked around in Google and tried every given solution, but it's still the same.
I cannot get my code to work. I have a list of integers, and I need to give every element to different variables.
dmy = input('What is your date? Please put in like this: 2.11.2016')
dmy.strip(".")
dmy = [int(x) for x in dmy.split('.')]
list(dmy)
print(dmy)
dd = dmy(0)
mm = dmy(1)
yy = dmy(2)
The first part of the code is working. I get the error while trying to give the list element to another variable so this dmy(0) does not work. But it is in all the books I have this way?
I use python 3.5.2
I see what you are trying to do. An element in the list is obtained by list[index] format. While you are trying to call as list(index) which python is interpreting as function call and hence throwing you error:
TypeError: 'list' object is not callable
Corrected code:
dmy = input('What is your date? Please put in like this: 2.11.2016')
dmy.strip(".")
dmy = [int(x) for x in dmy.split('.')]
list(dmy)
print(dmy)
dd = dmy[0]
mm = dmy[1]
yy = dmy[2]
>>> dd = dmy[0]
>>> mm = dmy[1]
>>> yy = dmy[2]
>>> dd
2
>>> mm
11
>>> yy
2016
>>>