ex: List=['hjk',23,4.5]
creating a blank list
list=[]
Create Multidimension List
List=[1,2,3,[4,5,6]]
Accessing element from list:
List[i]
list[:]
list[i:j]
Accessing element from Multi dimensional list
list[i][j]
Negative Indexing:
list[-1]
Length of string:
len(list)
Taking input of python list:
ex1:
s=input()
l=s.split()
ex2:
list(map(int,input().strip().split()))
Adding element to a python list:
- Append: we can add element at the end of list
- Insert: we can add element anywhere in the list
- Extend: It is used to add multiple element at the same time at the end of list
Append:
append element
list.append(1)
append list
list.append([1,2,3])
append tuple
list.append((1,2,3))
Insert Method:
list.insert(location,element)
Extend:
l.extend([1,4,5])
Remove elements from list:
remove(): it removes the element from the list and throws error when the element doesn't exist in the list.
pop(): it removes element from the list based on index, if we don't provide index it removes last element from list.
List Comprehension: creating a list from other iterable like tuples, array, string.
1. Clear(): Remove all item from the list
lis.Clear()
2. Index(): Returned the index of first matched item
lis.index(element,start,end)
3. Count(): Returned the count of number of item passed as an argument.
lis.Count()
4. Sort():
lis.Sort()
5. Reverse()
lis.reverse()
6. del[a:b]
7. Copy()
Using Slicing method:
a=[1,2,3,4]
b=a
b[0]='a'
print(a,b)
Swallow Copy: Any modification in new list won't be reflected in original list. but if we modify nested list element changes are reflected in both list as they are point to same reference.
1. list.copy()
2.
import copy
copy.copy(list)
import copy
a=[1,2,4,4,[3,4,5]]
b=copy.copy(a)
b[4][0]=1
print(a,b)
Deepcopy: When we modify a new list, only new list will be modified.
import copy
a=[1,2,4,4,[3,4,5]]
b=copy.deepcopy(a)
b[4][0]=1
print(a,b)
https://www.geeksforgeeks.org/python-lists/