What are the python list methods?

The list is majorly used data structure in python. The list is Mutable. So, we can change the list and manipulate list. Following are the major python list methods used by It industry
  1. append()append method is used to append the data in list. You can append single item in the existing list. 
    Example,languages = [‘Python’, ‘Java’]
    languages.append(‘Ruby’)
    Output:[‘Python’, ‘Java’, ‘Ruby’]
  2. extend()extend method is used to add the one list items to end of other list items. You can add the existing list to another list.
    Example,languages = [‘Python’, ‘Java’]
    languages.extend([‘Ruby’, ‘C#’])
    Output:[‘Python’, ‘Java’, ‘Ruby’, ‘C#’]
  3. pop()A pop method is used to pop the element from the list. We just need to mention the list index that needs to pop from the list. 
    Example,countries = [‘INDIA’, ‘USA’, ‘RUSSIA’, ‘CHINA’]
    removed_country = countries.pop(3)
    print countries
    print removed_country
    Output:[‘INDIA’, ‘USA’, ‘RUSSIA’]
    CHINA
  4. count()count method is used to count the number of time occurrence of the element. Like if you want to find how the number of occurrence of the word ‘hello’ you can use count function.
    Example,words = [‘hello’, ‘India’, ‘hello’, ‘USA’]
    word_count = words.count(‘hello’)
    print word_count
    Output:> 2
  5. insert()Insert method is used to insert the particular element at a particular index in the list. 
    Example,words = [‘hello’, ‘India’, ‘hello’, ‘USA’]
    words.insert(2, ‘new’)
    print words
    Output:[‘hello’, ‘India’, ‘new’, ‘hello’, ‘USA’]
  6. remove()Remove method is used to remove the particular element from the list.
    Example,words = [‘hello’, ‘India’, ‘new’, ‘hello’, ‘USA’]
    words.remove(‘new’)
    print words
    Output:[‘hello’, ‘India’, ‘hello’, ‘USA’]
  7. sort()Sort method is used to sort the list elements. You can sort the list by ascending or descending order.
    Example,l1 = [‘a’, ’n’, ‘t’, ‘k’]
    print l1.sort()
    print l1.sort(reverse=true)
    Output:
    [‘a’, ’k’, ‘n’, ‘t’]
    > [‘t’, ’n’, ‘k’, ‘a’]
That’s it these are the regularly used list methods in python.

No comments:

Powered by Blogger.