LISTS in Python
LISTS in Python
Output: 8
Python allows negative indexing for its sequences. The index of -
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
#Add Elements
add one item to a list using append()
#Change Elements method
add several items using extend()
= operator with index
insert one item at a desired location by
>>> marks=[90,60,80] using the method insert()
>>> marks.append(50)
>>> print(marks) >>> print(marks)
[90, 60, 80] [90, 100, 80, 50]
>>> marks[1]=100
>>> marks.extend([60,80,70])
>>> print(marks)
>>> print(marks)
[90, 100, 80] [90, 100, 80, 50, 60, 80, 70]
>>> marks.insert(3,40)
>>> print(marks)
[90, 100, 80, 40, 50, 60, 80, 70]
remove() method to remove the given item
delete one or more items from a
list using the keyword del. >>> marks=[90,60,80]
>>> marks.remove(80)
It can even delete the list entirely.
>>> print(marks)
>>> print(marks) [90, 60]
[90, 100, 80, 40, 50, 60, 80, 70] >>> marks.remove(100) delete items in a list
Traceback (most recent call last):
by assigning an
File "<pyshell#1>", line 1, in <module>
empty list to a slice
>>> del marks[6] elements.
marks.remove(100)
>>> print(marks) marks=[100,20,30]
ValueError: list.remove(x): x not in list >>> marks[1:2]=[]
[90, 100, 80, 40, 50, 60, 70] pop() method to remove an item at the given index. >>> print(marks)
>>> del marks >>> marks=[100,20,30] [100, 30]
>>> marks.pop()
>>> print(marks)
30
Name Error: name 'marks' is not >>> print(marks)
defined
[100, 20]
clear() method to empty a list.
>>> >>> marks.pop(0)
>>> marks.clear() 100
>>> print(marks) >>> print(marks)
[] [20]
>>> marks.extend([40,50,60,70])
>>> marks
>>> marks.pop()
60
Slicing [::] (i.e) list[start:stop:step]
Concatenation = +
Repetition= *
Membership = in
Identity = is
append() - Add an element to the end of the list