I have a list of city names alphabetically sorted as 'str' and I want to make another new list taking those city names with 'i' as his 3rd character using list comprehension.
I've tried so many things, but the most intuitive for me is:
`new_list = [word for word in old_list if word[2] == 'i']
And I dont know why, but get this error:
IndexError= string index out of range
I expected to get something like:
new_list = ['Beijing', 'Idil', 'Zhitiqara', ...]
It has to be using list comprehension.
CodePudding user response:
Some of your words have two characters. You should only apply this rule to words of three characters or more.
do:
new_list = [word for word in old_list if len(word) >= 3 and word[2] == 'i']