Output of Python Program | Set 4

Difficulty level : Intermediate
Predict the output of following Python Programs.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
  
print nameList[1][-1]

chevron_right


Output:

k

Explanation:
The index position -1 represents either the last element in a list or the last character in a String. In the above given list of names “nameList”, the index 1 represents the second element i.e, the second string “Pratik” and the index -1 represents the last character in the string “Pratik”. So, the output is “k”.

 

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
  
pos = nameList.index("GeeksforGeeks")
  
print pos * 5 

chevron_right


Output:

An Exception is thrown, ValueError: 'GeeksforGeeks' is not in list  

Explanation:
The task of index is to find the position of a supplied value in a given list. In the above program the supplied value is “GeeksforGeeks” and list is nameList. As GeeksforGeeks is not present in the list, an exception is thrown.

 

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

geekCodes = [1, 2, 3, 4]
  
geekCodes.append([5,6,7,8])
  
print len(geekCodes)

chevron_right


Output:

5

Explanation:
The task of append() method is to append a passed obj into an existing list. But instead of passing a list to the append method will not merge the two lists, the entire list which is passed is added as an element of the list. So the output is 5.

 

Program 4:

filter_none

edit
close

play_arrow

link
brightness_4
code

def addToList(listcontainer):
    listcontainer += [10]
  
mylistContainer = [10, 20, 30, 40]
addToList(mylistContainer)
print len(mylistContainer)

chevron_right


Output:

5

Explanation:
In Python, everything is a reference and references are passed by value. Parameter passing in Python is same as reference passing in Java. As a consequence, the function can modify the value referred by passed argument, i.e. the value of the variable in the caller’s scope can be changed. Here the task of the function “addToList” is to add an element 10 in the list, So this will increase the length of list by 1. So the output of program is 5.

This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.