Open In App
Related Articles

Output of Python Program | Set 4

Improve Article
Save Article
Like Article

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

Program 1:

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



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:

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


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

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


Program 3:

geekCodes = [1, 2, 3, 4]
# List will look like as [1,2,3,4,[5,6,7,8]]
print len(geekCodes)
#new list will be appended at the index 4 of geekCodes.



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:

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



In Python, everything is a reference, and references are passed by value. Parameter passing in Python is the 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 the list by 1. So the output of the program is 5.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Sep, 2023
Like Article
Save Article
Similar Reads