Python Lists are used to store multiple values in a single variable. Lists are created using square brackets in the order of 0,1,2,3,… N
NAMES = [“John”, “Paul”, “George”, “Ringo”]
AGES = [20, 21, 22, 23]
JOHN = NAMES[0]
PAUL = NAMES[1]
print(JOHN)
print(PAUL)
List slicing is the most used technique using the simple slicing operator i.e. colon(:) – where to start the slicing
List slicing in Python is a common practice and can be used both with positive indexes as well as negative indexes. The below diagram illustrates the technique of list slicing:
# Initialize Python list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[1:5])
#Output
[70, 30, 20, 90]
So from example list of Names above
JOHN_PAUL = NAMES[:2]
print(JOHN_PAUL)
#Output
[‘John’, ‘Paul’]
This is picking two elements from the start of 0 element
So the Syntax is
[Start:Stop:Step]
To Reverse the list it can be following, that means: no start point, no stop point, step by -1 each time
REVERSE = NAMES[::-1]
print(REVERSE)
#Output
[‘Ringo’, ‘George’, ‘Paul’, ‘John’]
To skip every second element
EVERY_OTHER = NAMES[::2]
print(EVERY_OTHER)
#Output
[‘John’, ‘George’]
Python list containing numbers can support sum, minimum and maximum
print(sum(AGES))
print(min(AGES))
print(max(AGES))
#Output
86
20
23
All other built-in methods that the Python list supports are as follows
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |