Python List
Python List
List = [1, 2, 3, 4, 5, 6]
print(List)
List[2] = 10; Output:
print(List)
[1,
List[1:3] = [89, 78]
2, 3, 4, 5, 6]
print(List) [1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5,
6]
Python List copy() Method
# Creating a list
evenlist = [6,8,2,4] # int list
copylist = []
# Calling Method
copylist = evenlist[:] # Copy all the element
s
# Displaying result
print("Original list:",evenlist)
print("Copy list:",copylist)
Python List insert(i,x) Method
# Creating a list
list = ['1','2','3']
for l in list: # Iterating list
print(l) Output:
1 2 3 After inserting:
1 2 3 ['4', '5', '6']
list.insert(3,['4','5','6'])
print("After inserting:")
for l in list: # Iterating list
print(l)
Python List pop() Method
# Creating a list
list = ['1','2','3']
for l in list: # Iterating list
print(l)
list.pop(2)
print("After poping:")
for l in list: # Iterating list
print(l)
Output:
1 2 3 After poping: 1 2
Python List remove(x) Method
# Python list remove() Method
# Creating a list
list = ['1','2','3']
for l in list: # Iterating list
print(l)
list.remove('2')
print("After removing:")
for l in list: # Iterating list
print(l)
output
1 2 3 After removing: 1 3
Python List remove() Method
If list contains duplicate elements, the
method will remove only first occurred
element. See the example below.
Python list remove() Method
# Creating a list
list = ['1','2','3','2']
for l in list: # Iterating list
print(l)
list.remove('2')
print("After removing:")
for l in list: # Iterating list
print(l)
Output:
1 2 3 2 After removing: 1 3 2
Python List count() Method
# Creating a list
apple = ['a','p','p','l','e']
# Method calling
count = apple.count('p')
# Displaying result
print("count of p :",count)
Python List sort() Method
# Creating a list
apple = ['a', 'p', 'p', 'l', 'e'] # Char list
even = [6,8,2,4] # int list
print(apple)
print(even)
# Calling Method
apple.sort()
even.sort()
# Displaying result
print("\nAfter Sorting:\n",apple)
print(even)
List sort
# Creating a list
even = [6,8,2,4] # int list
# Calling Method
#apple.sort()
even.sort(reverse=True) sort in reverse o
rder
# Displaying result
print(even)
Python List clear() Method
# Creating a list
list = ['1','2','3']
for l in list: # Iterating list
print(l)
list.clear()
print("After clearing:")
for l in list: # Iterating list
print(l)
Output:
1 2 3 After clearing: