Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.

Difficulty level: Intermediate Predicts the output of the following Python programs.

A program:

nameList = ['Harsh'.'Pratik'.'Bob'.'Dhruv']

print nameList[1] [-1]
Copy the code

Output:

ķ
Copy the code

Note: Index position -1 represents the last element in a list or the last character in a string. In the list of names “nameList” given above, index 1 represents the second element, the second string “Pratik”, and index -1 represents the last character in the string “Pratik”. Therefore, the output is “k”.

Program 2:

nameList = ['Harsh'.'Pratik'.'Bob'.'Dhruv']

pos = nameList.index("haiyong")

print pos * 5
Copy the code

Output:

An Exception is thrown, ValueError: 'haiyong' is not in l
Copy the code

Description: The task of an index is to find the location of a supplied value in a given list. In the above program, the provided value is “haiyong” and the list is nameList. Because haiyong is not in the list, an exception is thrown.

Three procedures:

geekCodes = [1.2.3.4]

# list will look like [1,2,3,4,[5,6,7,8]]
geekCodes.append([5.6.7.8])
print len(geekCodes)


print(geekCodes)
# The new list will be appended to index 4 of geekCodes.
Copy the code

Output:

5 
[1.2.3.4[5.6.7.8]]
Copy the code

Note: The job of the append() method is to append the obJ passed to the existing list. However, passing a list to the Append method does not merge the two lists, but adds the entire list passed as an element of the list. So the output is 5.

Four procedures:

def addToList(listcontainer) :
	listcontainer += [10]

mylistContainer = [10.20.30.40]
addToList(mylistContainer)
print len(mylistContainer)
Copy the code

Output:

5
Copy the code

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. Therefore, functions can modify the values referenced by passing arguments, that is, they can change the values of variables in the scope of the caller. The job of the “addToList” function here is to add an element 10 to the list, so this increases the length of the list by 1. So the output of the program is 5.

If you find anything wrong, let me know in the comments section below, learn from each other and make progress together!