Wednesday, May 3, 2023

#PYTHON(DAY7)List methods in python

                                             #PYTHON(DAY7)

Methods in Python

Python List Methods has multiple methods to work with Python lists

We use dir() function to print the built-in list methods

append()

  • append is used to add another element to the list and this element will be added at the end

Note: we can not append 2 elements into the list at a time

so, from the above code we get the error as list.append() takes exactly one value

extend()

  • extend is used to add two or more than two elements to end of the list
  • these values/elements should be passed in container

And the expected output for the above code is: [1,2,3,4,[5,6]]

count()

  • count will return the frequency of given element

And the expected output is:

insert()

  • insert as name suggests, is going to insert a new element at the specified index position
  • index takes two values i.e index and value

And the expected output is:

remove()

  • remove() is used to remove the specified element
  • it removes the first occurence

And the expected output is: here the first occurence is removed

pop()

  • pop removes the element at given index position, if no index value is passed, the last element will popped out
  • the discard/ejected element can be captured/assigned to a new for further use

And the expected output is:

Note: as the element is popped out, the index values changes

so, from the below code we get the error as pop index out of range

However, the remove() works on the elements and pop() works on indexes of elements

reverse()

  • it reverses the list

And the expected output is:

sort()

  • sorting in ascending or descending

And the expected output is:

And the expected output is:

copy()

  • copy is used to store the list in different location to stor it in the different location

clear()

  • it is going to erase all the elements from the list and returns an empty list

And the expected output is: [ ] (empty list)

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...