Doubt in python lists

Can anyone please explain how does the 2nd line of code work?

1)"words = [‘Emotan’,‘Amina’,‘Ibeno’,‘Santwala’]
2)new_list = [(word[0],word[-1])for word in words if len(word) > 5]
3)print (new_list)

Hello, @pravar.

Please format your code for proper display when you post it. See the Python Discourse Quick Start page for advice regarding how to post code snippets, error messages, etc. As explained there, you can place your code between two lines of triple backticks to format it.

The second line of your code contains a list comprehension that loops though the items in the words list. For each item that contains more than five characters, it creates a tuple that contains the first and the last character within that item. In the list comprehension, (word[0], word[-1]) represents that tuple. Note the two subscripts within the square brackets, namely 0 and -1. The first of those two accesses the character at index 0 in the item from the words list, and the second of those two subscripts, -1, accesses the final character in that item. When running the program, you should see the following output:

[('E', 'n'), ('S', 'a')]

For official documentation about list comprehensions, see 5.1.3. List Comprehensions.

Hey, just to add on what @Quercus has explained to you if you find list comprehension a little challenging then the usual for.. loop will make it easy to for you to understand…

words = ['Emotan','Amina','beno','Santwala']
# new_list = [(word[0],word[-1]) for word in words if len(word) > 5]
# print (new_list)

new_list = []  # we initialize a new list that we will use to store the word that will meet the criteria len(word) > 5

for word in words: # then we loop through each word
    if len(word) > 5:  # now only if the length of the word is > 5 we then pick the first and last character of the word
        print(f'{word} has a length greater than 5, which is {len(word)}')
        # (word[0], word[-1]) # was thinking and trying of storing it in a variable first then use it later but ignore it

        new_list.append((word[0], word[-1]))  # these are the positional args, 0 for first chacter in a word
                                              # note since append requires to pass one arg then we enclose the extracted caracters in atuple to make it one

but you have to admit that list comprehension gets the job done neatly and in a concise manner… cheers

1 Like

Thanks for the nice comparative for loop example, @kyle.

Here is some additional reference material that may be helpful with comparison of the details within the code examples: