Most commonly used list operations in Python

python @ Freshers.in

Here we will describe the commonly used list operations in Python

# How to create an empty list ?
# First way
empty_list = []
print("empty_list : ",empty_list)
# Second  way
empty_list = list()
print("empty_list : ",empty_list)
# How to create a list ?
my_list = ['Sam', 'Peter', 'Roy', 'Kelly']
print("my_list" , my_list)
# How to examine a list ?
# print element 0
my_list[0]
print(my_list[0])
# How to get the total number of elements in a list ?
len(my_list)
print(len(my_list))
# How to modify a list (does not return the list) ?
# How to append element to end ?
my_list.append('Rinu')
print(my_list)
# How to append multiple elements to end ?
my_list.extend(['King', 'Johny', 'Honey', 'Pink'])
print(my_list)
#  How to insert element at index 0 (shifts everything right)  ?
my_list.insert(0, 'maggie')
print(my_list)
# How to searches for first instance and removes it ?
my_list.remove('Pink')
print(my_list)
# How to remove element 0 and returns it ?
my_list.pop(0)
print(my_list)
# How to removes element 0 (does not return it) ?
del my_list[0]
print(my_list)
# How to replace element 0 ?
my_list[0] = 'Twinkle'
print(my_list)
# How to concatenate lists (slower than 'extend' method) ?
neighbors = my_list + ['car','bike','truck']
print(my_list)
# How to find elements in a list ?
my_list.count('King') # How to counts the number of instances ?
print(my_list)
my_list.index('Johny') # How to returns index of first instance ?
print(my_list)
# How to do list slicing [start:end:stride] ?
weekdays = ['Mon','Tues','Wed','Thurs','Fri']
print(weekdays)
weekdays[0] # How to get element 0 ?
print(weekdays)
weekdays[0:3] # How to get elements 0, 1, 2 ?
print(weekdays)
weekdays[:3] # How to get elements 0, 1, 2 ?
print(weekdays)
weekdays[3:] # How to get elements 3, 4 ?
print(weekdays)
weekdays[-1] # How to get last element (element 4) ?
print(weekdays)
weekdays[::2] # How to get every 2nd element (0, 2, 4) ?
print(weekdays)
weekdays[::-1] # How to get backwards (4, 3, 2, 1, 0) ?
print(weekdays)
# Alternative method for returning the list backwards ?
print(weekdays)
list(reversed(weekdays))
print(weekdays)
# How to sort a list in place (modifies but does not return the list) ?
my_list.sort()
print(my_list)
# How to sort in reverse ?
my_list.sort(reverse=True)
print(my_list)
# How to get sort by a key ?
my_list.sort(key=len)
print(my_list)
Author: user

Leave a Reply