Untitled

List Methods

Following example shows python list methods :

my_list = [3,8,1,6,0,8,4]

print(my_list.index(8))
#Output 1

print(my_list.count(8))
#Output 2

print(my_list.sort())
#sorts the list in ascending order

print(my_list.reverse())
#sorts the list in descending order

list1 = [3,4,5,200,5,25,1,3]
print(list1.extend([34,5]))
#appends 34,5 to the given list
#output [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]

Lists as Arguments

def my_function(food):
    for x in food:
        print (x)

fruits =["apple", "banana", "cherry"]
my_function(fruits)

apple, banana, cherry are passed into food as arguments and then the code iterates it over and prints each individual index value.

Slicing

Lst[ Initial : End : Step ]
list1 = [2,3,2,14,25]
print(list1[::-1])

#output [25, 14, 2, 3, 2]
>>>names = ['Afzal', 'Saif', 'Charlie', 'Aman']
>>>print(names[-1][-1])

Passing the slice operator twice gives the last index of the First list, Aman then gives the last index of it that is n

Comparing Lists

Copying Lists

List Comprehension