twalker
0
Q:

list python methods

list.append(x) # append x to end of list
list.extend(iterable) # append all elements of iterable to list
list.insert(i, x) # insert x at index i
list.remove(x) # remove first occurance of x from list
list.pop([i]) # pop element at index i (defaults to end of list)
list.clear() # delete all elements from the list
list.index(x[, start[, end]]) # return index of element x
list.count(x) # return number of occurances of x in list
list.reverse() # reverse elements of list in-place (no return)
list.sort(key=None, reverse=False) # sort list in-place
list.copy() # return a shallow copy of the list
43
#Objects can also contain methods. Methods in objects are functions that belong to the object.
#Let us create a method in the Person class:

class Person:
  
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self): # This is a method
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
1
Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, list doesn’t need a built-in function for creation of list.

Note – Unlike Sets, list may contain mutable elements.

# Python program to demonstrate  
# Creation of List  
  
# Creating a List 
List = [] 
print("Blank List: ") 
print(List) 
  
# Creating a List of numbers 
List = [10, 20, 14] 
print("\nList of numbers: ") 
print(List) 
  
# Creating a List of strings and accessing 
# using index 
List = ["Geeks", "For", "Geeks"] 
print("\nList Items: ") 
print(List[0])  
print(List[2]) 
  
# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Geeks', 'For'] , ['Geeks']] 
print("\nMulti-Dimensional List: ") 
print(List) 

Output:
Blank List: 
[]

List of numbers: 
[10, 20, 14]

List Items
Geeks
Geeks

Multi-Dimensional List: 
[['Geeks', 'For'], ['Geeks']]
3

New to Communities?

Join the community