Prerequisite -
Predict the output of the following Python programs.
6
Explanation:
The beauty of python list datatype is that within a list, a programmer can nest another list, a dictionary or a tuple. Since in the code there are 6 items present in the list the length of the list is 6.
- Program 2
['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
['python', '@', 'for']
['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
['python', '@', 'for']
['python', 'Geeks']
['Geeks', 'Geeks', 'learning']
Explanation:
In python list slicing can also be done by using the syntax listName[x:y:z] where x means the initial index, y-1 defines the final index value and z specifies the step size. If anyone of the values among x, y and z is missing the interpreter takes default value.
Note:
1. For x default value is 0 i.e. start of the list.
2. For y default value is length of the list.
3. For z default value is 1 i.e. every element of the list.
- Program 3
No Output
Explanation:
Unlike addition or relational operators not all the arithmetic operators can use lists as their operands. Since - minus operator can't take lists as its operand no output will be produced. Program will produce following error.
TypeError: unsupported operand type(s) for -: 'list' and 'list'
[]
Explanation:
As one would expect, attempting to access a member of a list using an index that exceeds the number of members (e.g., attempting to access list[10] in the list above) results in an IndexError. However, attempting to access a slice of a list at a starting index that exceeds the number of members in the list will not result in an IndexError and will simply return an empty list.
- Program 5