Open In App

Output of Python Program | Set 4

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

Program 1:




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


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:




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


Output:

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

Explanation:
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]]
geekCodes.append([5,6,7,8])
print len(geekCodes)
  
  
print(geekCodes)
#new list will be appended at the index 4 of geekCodes.


Output:

5
[1,2,3,4,[5,6,7,8]]

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:




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


Output:

5

Explanation:
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.



Last Updated : 11 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads