append() functiondel command or the
.remove() functionlottery_numbers = [1,2,3,4,5,6]
bonus = 7
lottery_numbers.append(bonus)
# print the first element
print(lottery_numbers[0])
# print the last element
print(lottery_numbers[6])
print(lottery_numbers)
lottery_numbers.remove(5) # Removes first occurrence of value 5 in list
del lottery_numbers[0] # Removes the 0th element of the list
print(lottery_numbers)
lottery_numbers[3] = 42
print(lottery_numbers)
Givest the output:
1
7
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 6, 7]
[2, 3, 4, 42, 7]
[i:j] syntax where i and j are indexes.
my_list = ['M','A', 'N', 'T', 'I', 'D']
print(my_list[1:4])
my_string = 'MANTID'
print(my_string[1:4])
Gives the output:
['A', 'N', 'T']
ANT
sort() function which modifies the
list in place.my_list = [5,4,3,2,7]
print(my_list)
my_list.sort()
print(my_list)
Gives the output:
[5, 4, 3, 2, 7]
[2, 3, 4, 5, 7]
l = [5,4,3,2,7]
l.sort(reverse=True)
print(l) #prints list in descending order
Gives the output:
[7, 5, 4, 3, 2]