Home > Software engineering >  Python indexing question within a function
Python indexing question within a function

Time:12-09

can someone explain line by line what's going on here in this function? Particularly the indexing numbers you see next to the return and how they make sense?

def animal_crackers(text):
    wordlist = text.split()
    return wordlist[0][0] == wordlist[1][0]

CodePudding user response:

  • text is a str

  • wordlist being a list of the words, as .split() separates on spaces

  • wordlist[0] the first word, wordlist[0][0] first char of first word

  • wordlist[1] the second word, wordlist[1][0] first char of second word

So you check if the first char of the 2 first words are same

print(animal_crackers("wa wb"))  # True
print(animal_crackers("va wb"))  # False

More details

animal_crackers("wabc wdef")

text=           'wabc wdef'
wordlist=       ['wabc', 'wdef']
wordlist[0]=    'wabc'       
wordlist[0][0]= 'w'       
wordlist[1]=    'wdef'       
wordlist[1][0]= 'w'

CodePudding user response:

str.split() returns a list of strings. For example "I am hungry".split() returns ["I", "am", "hunger"].

str[index] returns the character at that index. So "Foo"[0] returns "F"

So wordlist[0] returns the first string in the text that was split, and so wordlist[0][0] returns the first character of the first word in text. So wordlist[0][0] == wordlist[1][0] returns true if the first and second word of text start with the same letter.

CodePudding user response:

say, for example,

text = "This is my text"

Then text.split() is:

`['This', 'is', 'my', 'text']`

This list is assigned to the variable wordlist.

wordlist[0] is This, wordlist[1] is is, and so on.

The second index refers to the letters in each word.

so wordlist[0][0] is T, wordlist[0][1] is h, etc.

wordlist[0][0] == wordlist[1][0] asks if the first letter of the first word is the same as the first letter of the second word.

In the example This is my text, that is not the case, so the function will return False.

CodePudding user response:

wordlist = text.split()
return wordlist[0][0] == wordlist[1][0]

First-line splits text into a list and saves its value in the variable wordlist. and the second line checks if the first letter of the first word equals the first letter in the second word. The way it work is the first index represents the word and second index represents the letter in that word. For Example

text = "Hello there"
wordlist = text.split()
print(wordlist[0]) #Returns "Hello"
print(wordlist[0][0]) #Returns "H"
print(wordlist[1][0]) #Returns "t"

and so on.

Hope my answer was helpful.

  • Related