+ 2

I am not getting how this particular output is getting generated, can anyone please help me and explain the logic behind it?

words = ["Python","fun"] words.insert(5,"is") words.insert(4,"life") print(words) I typed the above code and and got the output as follows: ['Python', 'fun', 'is', 'life']

13th Feb 2017, 6:54 AM
Priyanka P
Priyanka P - avatar
5 Answers
+ 10
"words" creates a list which holds strings. it's like a real life list, with a bunch of writing in a certain order. [edit: removed dictionary explanation, I get list and dictionary mixed up sometimes!] words.insert adds a string (which is pretty much anything with quotes like "Hello!") according to what's in the parentheses to the words list. you could have another list and insert to it like: colors=["red"] colors.insert(1,"blue") inside the first words.insert parentheses is a number, and then a string. the number is what chooses what position the string goes to in the list. the order of the list starts at zero and counts up: foods=["pizza","ice cream","toast"] So pizza would be #0, ice cream #1 and toast #2 after the number you add a comma to seperate the two, then the string. In this case they decide to skip ahead and add in 4 and 5. Here's where it gets a little weird. "is" is position number 5, and "life" is number 4, so it should be "life" "is" right? No. Python preforms tasks from top to bottom, and "is" comes first. It adds it's position, but since there are no strings in the positions before it, it drops down to the max position, which is 2. Then life comes in and does the same. Also, insert won't replace a string, it'll move each string up from which spot it takes. so: places=["tokyo","new york"] places.insert(1,"berlin") will make it: places=["tokyo","berlin","new york"] finally, there is a print. Print outputs text for you to read. Any string you put inside it will be outputted for you to read in the console. in this case, the variable (words) the holds the list is put inside print, which makes it output all the strings that words has in its list. Any questions?
13th Feb 2017, 7:18 AM
Ahri Fox
Ahri Fox - avatar
+ 7
@ChaoticDawg fixed it! thanks. I often confuse dictionary and list.
13th Feb 2017, 7:51 AM
Ahri Fox
Ahri Fox - avatar
+ 4
words is a list, the insert() function will insert the word "is" at 5 index and "life" at 4 but since that indexes are not reached yet cause "python" is 0 and "fun" is 1 that will work as the append() function just inserting the word to the final of the list
13th Feb 2017, 7:14 AM
Kawaii
Kawaii - avatar
+ 3
Thanks a lot :) I understood it now. @N3tW0rk and @Ahri Fox
13th Feb 2017, 7:26 AM
Priyanka P
Priyanka P - avatar
+ 1
@Ahri Fox Spot on with the exception of your second sentence. I wouldn't refer to it as a dictionary so as not to confuse. A dictionary is a [key: value] pair where the key acts as the index. words = ["first": "Python"] print(words["first"]) # outputs "Python"
13th Feb 2017, 7:43 AM
ChaoticDawg
ChaoticDawg - avatar