InterviewSolution
| 1. |
Lists are mutable. It means that the contents of the list can be changed after it has been created. Given a list1 of colors, 1. Write a command to change/override the fourth element of list1 as BLACK 2. Write a command to display the first three elements of the list1. 3. Write a command to find the total elements in the list1. list1 = ['Red','Green','Blue','Orange', 'pink', 'Purple','Magenta','Yellow'] |
|
Answer» hiiExplanation:list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type. Lists and strings — and other things that BEHAVE like ordered sets — are called sequences.9.1. List valuesThere are several ways to create a new list; the simplest is to enclose the elements in square brackets ( [ and ]):[10, 20, 30, 40]["spam", "bungee", "swallow"]The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (mirabile dictu) another list:["hello", 2.0, 5, [10, 20]]A list within another list is said to be nested.Finally, there is a special list that contains no elements. It is called the empty list, and is denoted [].Like numeric 0 values and the empty string, the empty list is false in a boolean expression:>>> if []:... print 'This is true.'... ELSE:... print 'This is false.'...This is false.>>>With all these ways to create lists, it would be disappointing if we couldn’t assign list values to variables or pass lists as parameters to functions. We can:>>> vocabulary = ["ameliorate", "castigate", "defenestrate"]>>> numbers = [17, 123]>>> empty = []>>> print vocabulary, numbers, empty['ameliorate', 'castigate', 'defenestrate'] [17, 123] []9.2. Accessing elementsThe syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string—the bracket operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index. Remember that the indices start at 0:>>> print numbers[0]17Any integer expression can be used as an index:>>> numbers[9-8]123>>> numbers[1.0]Traceback (most recent call last): File " |
|