The TypeError in python - python

I'm trying to make a challenge for one of the courses I'm following. I'm new to programming, but I'm eager to learn.
Can you tell me in detail why this error occurs to me and how do solve it.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
for i in default_names:
default_names[i]=default_names[i][0].upper()
i+=1
if i==len(default_names):
break
print default_names
the error: TypeError: list indices must be integers, not str

default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
print default_names

What you are looking for is :
for i,s in enumerate(default_names):
or simple:
for i in range(len(default_names)):
The mistake you are doing is that when you say for i in default_names: notice that i value is a string, not int as you are trying to use.
for i in default_names:
print(i)
Will give :
OUT: Justin
john
Emilee
jim
Ron
Sandra
veronica
Wiskley
So the actual code should be, assuming you are trying to convert each string in list to Upper case :
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
EDIT : The OP wants only First char to be Upper case, and since string are immutable, change of code to :
for i in range(len(default_names)):
default_names[i]=default_names[i][0].upper() + default_names[i][1:]

As you can see in your error: TypeError: list indices must be integers, not str. It's because to access the elements of a list, you have to use the index, which is an integer. Basing on the structure of your code, you might have come from a different language. Python's for loop is different from the other languages. It doesn't increment the variable you made over the loop, but rather it iterates over the elements and passes the value to the variable. I think it would be more suitable to use a while loop with the code you made since you have initialized your i to 0. E.g.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
while i < len(default_names):
default_names[i]=default_names[i].upper() #removed the [0] here
i+=1
#removed the other codes here
print default_names
As you become better in python, you can find more efficient ways to do these kinds of things. The result you wanted could be simply made through
default_names = [name.upper() for name in default_names]
which simply iterates all of the names, makes it upper case and saves it back to default_names

Related

Python 3 Error Missunderstanding (IndexError)

Here's my code
def abc(l,z):
L=[]
länge= len(L)
for x in range(0, länge+1):
L[x]+z
print(L)
abc(["1","2","3"],"-")
I want the program to output "1-2-3"
l in abc(l,z) should be a List out of Strings which combines "l" and "z" to a single String.
I'm getting an Index Error: list index out of range.
There are a couple of issues here.
First, range(0, länge+1) will stop at länge but your list only has indexes from 0 tolänge - 1, so that's one source for an IndexError.
Second, L[x]+z will give you another IndexError because L is empty but you try to access L[0] (and in the next iteration, where you don't get because of the error, L[1], L[2], and so on).
Third, even without an IndexError the statement L[x]+z will do nothing. You compute the value of L[x]+z but then you don't assign any variable to it, so it is immediately lost.
Fourth, in order to print your final result, put the call to print after the for loop, not inside. Consider using return instead of print if you actually want to do something with the result the function produces (make sure to educate yourself on the difference between print and return).
Fifth, you want to build a string, so the usage of the list L does not make much sense. Start with an empty string and add the current item from l and z to it in the loop body (coupled with a re-assignment in order to not lose the freshly computed value).
Lastly, there's no point in using range here. You can iterate over values in a list direclty by simply writing for x in l:.
That should give you enough to work with and fix your code for now.
(If you don't care why your function does not work and this is not an exercise, simply use str.join as suggested in the comments.)

order of items in the for loop

I have this data
1. def lem(str):
return synsets for every str
2. list_terms = list of terms
3. list_st = list of strings as input for the function
What needed here is to find in the list of terms any string as output of the function. The problem with me is the order of the items in the code below
if any(i in list_terms for i in lem(item) for item in list_st):
do somethind
This code gives the error
NameError: name 'item' is not defined
Can someone help ?
Hm, do you really need it to be a list comprehension here?
I think the problem is more clearly visible if you write this down more explicitly:
terms = []
for item in list_st:
for i in lem(item):
if i in list_terms:
terms.append(i)
if terms:
do_something
This is a bit ugly in that it follows the Arrow Anti Pattern, but makes a bit more clear what is going on here.
If you convert this to a list comprehension, remember that you need to reverse the order or the loop declarations (see the comment above).

how to loop through and get the last value

Hi i have the following code:
m= list()
for i in range (1,6):
set = base.Getentity(constants.ABAQUS,"SET",i)
m.append(set)
print(set)
and my result is
<Entity:0*17a:id:1>
<Entity:0*14g:id:2>
<Entity:0*14f:id:3>
<Entity:0*14a:id:4>
None
None
Here i have four elemnts in my set named set. Even though my code is written in ansa python, my question is very General
I would like to write a code which goes through the set and prints the last elemnt in my case
'<Entity:0*17a:id:4>'.
and aslo i dont want to use the range function so pls help me with writing the code.
I suggest you look at Iterators, that will help you loop through the list
If you don't want to use the range function, you can use xrange. It returns an xrange object, which is kind of like an iterator and generates the numbers on demand.
You are getting None as the last two values because there are no 'set' with the id 5 and 6 in your model
Use a filter before appending to the list m
m= list()
for i in range (1,6)
set = base.Getentity(constants.ABAQUS,"SET",i)
if set!=None:
m.append(set)
Now you can just call m[-1] for the last entity
hope this helps

Python KeyError: 0 when working with dictionary and functions

I'm new to Python so my question may seem easy to some but then again I'm stuck on my own so I need your help! This is the code that i am having trouble with:
def identify_language(sequence, **common_words):
result = {}
for i in common_words:
result[i] = 0
for i in func_op(sequence.lower()):
for j in common_words:
if i in common_words[j]:
result[j] += 1
return sort(result[0][0])
...
dictionary = {'cro':list_cro, 'eng':list_cro}
language = identify_language('I had a little lamb. It was called Billy.', **dictionary)
I am trying to identify language based on samples which are in list_cro and list_eng (and hopefully others). I am getting KeyError: 0. Additionally, sort and func_op are working fine i tested then separately. What may be the problem?
Also, if i change order of arguments in function (putting list as a first argument and string as second) i am getting syntax error.
Thanks for listening!
At the end of the function, result should look like this: {'cro': X, 'eng': Y}, where X and Y are numbers. I don't know what your dictionaries are, so I can't guess what the numbers are. Evaluating result['eng'] will produce a number, as will result['cro'], but there is no 0 key in this dictionary.
Further, the second indexing operation will also give you issues. result['eng'][0] will give you an error because result['eng'] is a number, and you can't index into a number.
What do you expect the output of this function to look like? Where is sort defined and what is it supposed to do?

The 'int' object is unsubscriptable

I have searched for nearly an hour online, but can't find anything. But I digress, line 6 keeps on returning TypeError: 'int' object is unsubscriptable. Please help me identify what causes this.
def __reassigner__(allL, currentRow, currentSpace):
changingRow=currentRow+1
newl=[-1]*24
while changingRow<8:
distance = changingRow-currentRow
newl[8:15]=allL[changingRow[0:7]] #Line 6, this one
if newl[currentSpace]==-1:
newl[currentSpace]= currentRow
if newl[currentSpace-distance]==-1:
newl[currentSpace-distance]= currentRow
if newl[currentSpace+distance]==-1:
newl[currentSpace+distance]= currentRow
allL[changingRow[0:7]]=newl[8:15]
changingRow+=1
return(allL)
The variable changingRow is an integer, but you try to slice it with changingRow[0:7]. Since this operation is not allowed on ints, you get the error.
I don't know what your intention was with that line. Maybe allL is a list of lists and you were going for allL[changingRow][0:7]?
changingRow in your code seems to be an integer (I assume that after line saying changingRow=currentRow+1). Unfortunately, in line 6, you try to obtain: changingRow[0:7], which doesn't work, since you're trying to access your integer value as if it was an array.
changingRow is an integer value. changingRow[0:7] would extract the first 7 elements of a list-like ("subscriptable") object, but an int has no such "elements" like the ones in lists and strings have.
What are you trying to achieve with changingRow[0:7]?
changingRow is an integer, you can't take indeces 0-7 from it
You can't access write changingRow[0:7] because changingRow is an integer. If you must access it using slice notation (for the first 8 digits or something) you can do str(changingRow)[0:7], but you probably have a design problem.

Categories