Using Python Start by assigning to variables monthsL and monthsT a list and a tu
ID: 3870698 • Letter: U
Question
Using Python
Start by assigning to variables monthsL and monthsT a list and a tuple, respectively, both containing strings 'Jan', 'Feb', 'Mar', and 'May', in that order.
Then attempt the following with both containers:
(a) Insert string 'Apr' between 'Mar' and 'May'.
(b) Append string 'Jun'.
(c) Pop the container.
(d) Remove the second item in the container.
(e) Reverse the order of items in the container.
(f) Sort the container.
Note: when attempting these on tuple monthsT you should expect errors.
Explanation / Answer
"""
Lists are mutable i.e they can be changed.
Tuples are immutable i.e they cannot be changed.
del,sort,reverse doesn't work with tuple as they are immutable but
We can get the operations done on tuple with the help of indexing.
"""
monthsL = [ 'Jan', 'Feb', 'Mar','May']
monthsT = ('Jan', 'Feb', 'Mar','May')
#Adding Apr between Mar and May
monthsL = monthsL[:3] + ['Apr'] + [monthsL[-1]]
monthsT = monthsT[:3] + ('Apr',) + (monthsT[-1],)
#Append string 'Jun'
monthsL.append('Jun')
monthsT = monthsT + ('Jun',)
#pop the container
monthsL.pop()
#Del operation is not done in tuples since they are immutable
monthsT = monthsT[:-1]
#remove second element in container
del monthsL[1]
monthsT = monthsT[:1] + monthsT[2:]
#reverse the order of items in the container
monthsL.reverse()
monthsT = monthsT[::-1]
#sort the container
monthsL.sort()
monthsT = sorted(monthsT)
print(monthsL)
print(monthsT)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.