Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
mylist=[5,12,16,17,12]
index=mylist.index(3)
print(index)
Output:
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
ValueError: 3 is not in list
I am trying to find the value output at position 3 but I do not understand the error message why it says '3' is not in list.
From my understanding, the argument passed to index() will just be the element position. In this case, there is an element in position '3' i.e 17.
Need advice on helping to understand the error message. Thank you.
The index function doesn't get the value at a specific index. It looks for a value and returns the index where it's found. Or throws an exception if the value isn't found.
If you want to get the fourth element in the list use "array" index syntax, like mylist[3].
This tutorial explains it.
The index function gives the position of the element you are looking for.
index=mylist.index(3) means you are looking for the position of element(3), which is not in mylist hence giving an error.
Now come to your question,
to find the element at particular position use mylist[index(an integer)].
So to find the element at 3rd position use mylist[3].
for basics follow indexing
The index() function of a list searches the list for the value passed as its parameter. If found, it will return the appropriate index (base 0). If not found, a ValueError exception will be raised. You are searching mylist for a value of 3 which doesn't exist - hence the exception. You probably meant mylist[3]
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
What is causing this error? Isn't it possible commenting out lines like this inside code?
for i in (Class_1, """Class_2, Class_3"""):
name = i.__name__
Class_1, Class_2 and Class_3 are classes declared before the upper code.
Error output:
> Traceback (most recent call last):
File "", line 2, in <module>
name = i.__name__
AttributeError: 'str' object has no attribute '__name__'
Process finished with exit code 1
Error message line edited to fit the example code
Remove the triple-quoted string """Class_2, Class_3""" to avoid iterating over it which is what you're doing in this case so it looks like for i in (Class_1,) (parenthesis are optional).
It seems you want to comment out those unnecessary sides, but please note that those triple-quotes strings technically aren't comments, so they can still affect the script in some areas you didn't intend.
What do you mean by
for i in (Class_1, """Class_2, Class_3"""):
When you iterate over this tuple, the second element is a string, thus causing the error.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#This will import time, so that I can break between lines
import time
import random
import os
#This will open the file, and will allow me to print it out
words =open("Words.txt", "r+")
print(words.read())
#This sets the different words to variables
x = 0
y = 0
z = 0
grid = 0
for i in words:
list_of_words[x] = i.rstrip()
x = x +1
grid = [words[i:i + 3] for i in range(0, len(words), 3)]
for x,y,z in grid:
print(x,y,z)
#This will close the word file
words.close
I've got the first part to work, but when it comes up to the second part it says I have to have an int in it. This is the error message:
Traceback (most recent call last):
File "C:\Users\Jamie\Documents\Jamie\Homework\Computing\Coureswork\Computer Science Courseword real.py", line 18, in <module>
for x,y,z in grid:
TypeError: 'int' object is not iterable
The error you're getting is because grid is 0 (which you initialized it to), rather than becoming a list when you assign a list comprehension to that name in the first loop.
That loop never does anything because you've already consumed the words file with words.read() near the top of the program. Iterating over the file does nothing, since you're already at the end. In order to read the file again, you either need to close and reopen it, or use words.seek(0) to rewind your position in the file. Or better yet, don't read the whole thing into a string if you don't need to.
Note that even after you fix the issue with reading the file, you'll have other problems. For instance, you've never defined list_of_words, so that will cause an exception. You're also trying to slice the file in the list comprehension you're assigning to grid. That's not legal.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
this is my first question here but I've visited this site many times to find answers.
I'm facing what seems to be a really dumb problem.
I'm trying to create a '2d' list in python but a syntax error is teasing me.
Here is my code:
def gen2darr(row, column): # generates an array
for in range row:
arr.append([]) # create the lines
for i in range row:
for in range column:
arr[i].append(float(int(row*column*random)))
# fills the array, float(int( because I want floats that 'are ints',
# ex: 2.0 or 152.0
and here is what I get:
for in range row:
^
SyntaxError: invalid syntax
I've tried putting a value in the for loop in this way:
for j in range row:
but I then get this:
for j in range row:
^
SyntaxError: invalid syntax
Can someone help me with this?
For me syntax error means I'm likely missing a bracket or a coma somewhere but I cannot find it.
If you want to use a range, then you need to call the function:
for j in range(row):
range is not part of the Python syntax, it is just another built-in object type.
The syntax is:
for j in range(row):
range is a function taking an argument. And you have to specify which variable you will use to iterate (j)
The range function have following syntax: range(limit 1, limit 2), you pass like argument a size of array you want.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Suppose I have a list containing 9 fields, and the 9th field is a string.
Then print(line) will print the entire line, print(line[9]) will return something like:
1/0:.:PASS:90:204,90:201,88:48,39:-204,0,-90:-48,0,-39:14:9,5:5
but print(line[9[0:1]])
will return
File "FileParser.py", line 9, in ?
print(line[9[0:1]])
TypeError: unsubscriptable object
If I assign line[9] to a second var, then I can manipulate it like a string, but this seems like a silly extra step.
Is there a way to index directly into the string while still part of the list?
Thank you
You can index it like this
line[9][0:1]
line[9] will get the actual string and you get the range of characters from that string.
When you do line[9[0:1]] you are trying to get the range of values from the number 9, which is not possible. That is why your code fails.
Since line[9] is a string, then you have to do
line[9][0:1]
Let's say line[9] = "some string". Then you can manipulate it with
line[9][0:1]
which will be equivalent to
"some string"[0:1]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
When I declare the variable for the string in the code it works, for example:
messagetoencode="readthis"
encodedMsg=[]
for letter in messagetoencode:
encodedMsg.append(encode[letter.upper()])
print "result is ", encodedMsg
However when I try and do the same operation with the user input it doesn't work:
lst = list(raw_input("Please enter a message to encode: "))
encodedMsg=[]
for letter in lst:
encodedMsg.append(encode[letter.upper()])
print "result is ", encodedMsg
and I get a traceback error, any ideas why?
Error:
Please enter a message to encode: hello
Traceback (most recent call last):
File "Untitled 3.py", line 27, in <module>
obfuse.append(encode[letter.upper()])
KeyError: 'O'
The problem is with the key O in the dictionary. It doesn't exist on the text, which is why no error happened. But if you include o in your input, you'll get this error.
Well, the real solution is to have the key'O' in your encoding dictionary.
To deal with unexpected input, you can do a check like this:
for letter in lst:
if letter not in encode:
raise KeyError("Sorry i don't know how to encode this letter!")
encodedMsg.append(encode[letter.upper()])
The problem is, O is not in the encode dictionary. If you want to assign a default value, instead of failing like this, you can use dict.get method like this
obfuse.append(encode.get(letter.upper(), None))
Now, this will return None if any of the keys are not found in encode. You might actually want to include a mapping for O in your code.