Prerequisite - Lists in Python Predict the output of the following Python programs. These question set will make you conversant with List Concepts in Python programming language.
list1[0]: physics
list1[0]: 1997
list1[-2]: ['chemistry', 1997, 2000]
list2[1:5]: [2, 3, 4, 5]
- Explanation: To access values in lists, we use the square brackets for slicing along with the index or indices to obtain required value available at that index.For N items in a List MAX value of index will be N-1. Statement 1 : This will print item located at index 0 in Output. Statement 2 : This will print item located at index -2 i.e.second last element in Output. Statement 3 : This will print items located from index 1 to end of the list. Statement 4 : This will print items located from index 1 to 4 of the list.
- Program 2
list1[1][1]: h
list1[1][-1]: y
- Explanation: In python we can slice a list but we can also slice a element within list if it is a string. The declaration list[x][y] will mean that 'x' is the index of element within a list and 'y' is the index of entity within that string.
- Program 3
list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009]
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]
- Explanation: When addition(+) operator uses list as its operands then the two lists will get concatenated. And when a list id multiplied with a constant k>=0 then the same list is appended k times in the original list.
- Program 4
index of element 105 is : 5
- Explanation: Statement 1 : will generate numbers from 100 to 110 and append all these numbers in the list. Statement 2 : will give the index value of 105 in the list list1.
- Program 5