LIST IN PYTHON

 Python has a set of built-in methods that you can use on lists/arrays.


Method Description

append() Adds an element at the end of the list

      fruits = ['apple', 'banana', 'cherry']

      fruits.append("orange")

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                 

                x = fruits.index("cherry")

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                

                fruits.remove("banana")


reverse() Reverses the order of the list

sort() Sorts the list

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort(reverse = True)

print(thislist)

list.sort(reverse=True|False, key=myFunc)

Parameter Description

reverse Optional. reverse=True will sort the list descending. Default is reverse=False

key Optional. A function to specify the sorting criteria(s)

# A function that returns the length of the value:

def myFunc(e):

  return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc)


PYTHON PROGRAM SYNTAX SERIES

Comments

Popular Posts