IndexError: string index out of range (enumerate) [duplicate] - python

This question already has answers here:
IndexError: string index out of range:
(5 answers)
Closed 2 years ago.
Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop.
I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?
>>> name = "Chris"
>>>
>>> my_list = []
>>>
>>> for key, value in enumerate(name):
... my_list.append(value[key])
... print (my_list)
...
The error I'm receiving:
['C']
Traceback (most recent call last):
File "<pyshell#7>", line 2, in <module>
my_list.append(value[key])
IndexError: string index out of range

What you are missing is that value is a single element string. Indexing at positions != 0 will result in an IndexError; during your first iteration that's what happens.
If you want to create it with your for loop, just append the value immediately:
for key, value in enumerate(name):
my_list.append(value)
Of course, enumerate is by no means required here, this can be simplified by calling list and supplying the string in question; Python will then create a list containing the contents of the string for you:
my_list = list(name)
For Python 3.x you can also unpack in a list literal with *:
my_list = [*name]
In all supplied snippets, the result of the operations is ['C', 'h', 'r', 'i', 's'] as required.

name = 'Chris'
my_list = list(name)
print(my_list)
Input: ['C', 'h', 'r', 'i', 's']
For one in each time:
for letter in name:
print(letter)

You are enumerating over a string ("Chris") which means that key and value will hold the following values during the iteration:
0 "C"
1 "h"
2 "r"
3 "i"
4 "s"
value[key] in the first iteration is ok, it returns 'C'.
In the second iteration, the index 1 is out of range for string "h".
What you probably want to do is this:
for i, value in enumerate(name):
my_list.append(value)
print (my_list)

An alternative way, to reach your goal:
>>>name ="Chris"
>>>list(name)
['C', 'h', 'r', 'i', 's']
For your example:
When iterating through a string in python, no enumeration is required.
>>>name = "Chris"
>>>my_list = []
>>>for i in name:
... my_list.append(i)
>>>my_list
['C', 'h', 'r', 'i', 's']

change my_list.append(value[key]) to my_list.append(value) in your code

Related

How do I replace a string at a index in python? [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 1 year ago.
So I already know how to remove a index like this:
i = "hello!"
i= i[:0] + i[1:]
print(i)
'ello!'
But how do I replace it?
So maybe I wanted to now put a H where the old h was but if I do this:
i[0] ="H"
I get this error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
i[0] ="H"
TypeError: 'str' object does not support item assignment
How do I fix this?
Strings are immutable in Python, so you can't assign like i[0] = 'H'. What you can do is convert the string to list, which is mutable, then you can assign new values at a certain index.
i = "hello!"
i_list = list(i)
i_list[0] = 'H'
i_new = ''.join(i_list)
print(i_new)
Hello!
Without creating a list you could also do:
i = "hello!"
i = "H" + i[1:]
More general:
def change_letter(string, letter, index): # note string is actually a bad name for a variable
return string[:index] + letter + string[index+1:]
s = "hello!"
s_new = change_letter(s, "H", 0)
print(s_new)
# should print "Hello!"
Also note there is a built in function .capitalize()
This is a duplicate of this post
As said there you have to make a list out of your string and change the char by selecting an item from that list and reassigning a new value and then in a loop rebuilding the string.
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
i = "hello!"
print(i) ## will print hello!
i = "H" + i[1:]
print(i) ## will print Hello!

Appending list(element) to another list gives an element by letter [duplicate]

This question already has an answer here:
What is the difference between a list of a single iterable `list(x)` vs `[x]`?
(1 answer)
Closed 3 years ago.
Sorry for this question, but I do not understand why the difference between the following results when adding an element to the list as a list itself to other list:
list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
list_a.append([word])
print("Append to dist_list single word: ", list_a)
Output: Append to list_a: [['HELLO'], ['WORLD']]
list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
list_a.append(list(word))
print("Append to list_a: ", list_a)
output: Append to list_a: [['H', 'E', 'L', 'L', 'O'], ['W', 'O', 'R', 'L', 'D']]
When you perform list() to a string, the string gets turned into a list that's separated for each individual value. For example:
a = 'string'
b = list(a)
b = ['s','t','r','i','n','g']
Therefore the difference comes because in the first case you are appending two items (both being strings) and in the second one, you are appending the string previously turned into a list with the logic explained above, hence you've appended a list for each string. This is the differnece in the results you are getting. First case add two strings, second case add two lists.

Python lists similitudes

I am looking to get the number of similar characters between two lists.
The first list is:
list1=['e', 'n', 'z', 'o', 'a']
The second list is going to be a word user inputted turned into a list:
word=input("Enter word")
word=list(word)
I'll run this function below to get the number of similitudes in the two lists:
def getSimilarItems(word,list1):
counter = 0
for i in list2:
for j in list1:
if i in j:
counter = counter + 1
return counter
What I don't know how to do is how to get the number of similitudes for each item of the list(which is going to be either 0 or 1 as the word is going to be split into a list where an item is a character).
Help would be VERY appreciated :)
For example:
If the word inputted by the user is afez:
I'd like the run the function:
wordcount= getSimilarItems(word,list1)
And get this as an output:
>>>1 (because a from afez is in list ['e', 'n', 'z', 'o', 'a'])
>>>0 (because f from afez isn't in list ['e', 'n', 'z', 'o', 'a'])
>>>1 (because e from afez is in list ['e', 'n', 'z', 'o', 'a'])
>>>1 (because z from afez is in list ['e', 'n', 'z', 'o', 'a'])
Sounds like you simply want:
def getSimilarItems(word,list1):
return [int(letter in list1) for letter in word]
What I don't know how to do is how to get the number of similitudes
for each item of the list(which is going to be either 0 or 1 as the
word is going to be split into a list where an item is a character).
I assume that instead of counting the number of items in the list, you want to get the individual match result for each element.
For that you can use a dictionary or a list, and return that from your function.
Going off the assumption that the input is going to be the same length as the list,
def getSimilarItems(list1,list2):
counter = 0
list = []
for i in list2:
for j in list1:
if i in j:
list.append(1)
else:
list.append(0)
return list
Based off your edit,
def getSimilarItems(list1,list2):
counter = 0
for i in list2:
if i in list1:
print('1 (because )'+i +' from temp_word is in list'+ str(list1))
else:
print("0 (because )"+i +" from temp_word isn't in list" + str(list1))
Look at Julien's answer if you want a more condensed version (I'm not very good with list comprehension)

Split the word by each character python 3.5 [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
I tried using all the methods suggested by others but its not working.
methods like str.split(), lst = list("abcd") but its throwing error saying [TypeError: 'list' object is not callable]
I want to convert string to list for each character in the word
input str= "abc" should give list = ['a','b','c']
I want to get the characters of the str in form of list
output - ['a','b','c','d','e','f'] but its giving ['abcdef']
str = "abcdef"
l = str.split()
print l
First, don't use list as a variable name. It will prevent you from doing what you want, because it will shadow the list class name.
You can do this by simply constructing a list from the string:
l = list('abcedf')
sets l to the list ['a', 'b', 'c', 'e', 'd', 'f']
First of all, don't use list as name of the variable in your program. It is a defined keyword in python and it is not a good practice.
If you had,
str = 'a b c d e f g'
then,
list = str.split()
print list
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Since split by default will work on spaces, it Will give what you need.
In your case, you can just use,
print list(s)
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Q. "I want to convert string to list for each character in the word"
A. You can use a simple list comprehension.
Input:
new_str = "abcdef"
[character for character in new_str]
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Just use a for loop.
input:::
str="abc"
li=[]
for i in str:
li.append(i)
print(li)
#use list function instead of for loop
print(list(str))
output:::
["a","b","c"]
["a","b","c"]

One word string made into a list of the letters

I have a list of words but I need to take the last item off the list, perform a function with the rest of the list then replace the last item. But for some reason when i go to to replace the last item, it does this...
>>> List = ['this', 'is', 'a', 'list']
>>> last = List[-1]
>>> others = List[:-1]
>>> others += last
>>> print others
['this', 'is', 'a', 'l', 'i', 's', 't']
Is there any way I can concatenate the list called last onto others but have it just one single element.
Try using append
others.append(last)
You can further simplify the code by doing this:
last = List.pop()
This removes the last element or List if no parameter is specified, and saves it in the variable last for you
Use append instead of +=:
>>> others.append(last)
Use:
others.append(last)
instead of
others += last
This is because:
When you are doing
list += ["somethingHere"]
it's equivalent to
list.extend(["somethingHere"])
According to the doc,
list.extend(L) = Extend the list by appending all the items in the given list
but
list.append(x) = Add an item to the end of the list
And what you need here is to " add an item " not to " append all the items in the given list " (all characters in this case.)
Please use one following:
others += [last]
others.append(last)
+ for list instances is iterating over element being added to it, thus iterating over string you get list of characters.
others += 'string'
others += ['s', 't', 'r', 'i', 'n', 'g']

Categories