Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: List comprehension to make a list of name with 'i' in the 3rd character from another list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expected to get something like:

new_list = ['Beijing', 'Idil', 'Zhitiqara', ...] 

It has to be using list comprehension.

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading