Lists
Lists are a mutable data type and we use square brackets to create a list.
Change List Elements
With the help of index numbers we can change the list elements.
Add List Elements
With the help of append, insert and extend we can add elements to lists.
append()
Append helps us to add the element to the end of our list.
insert(pos, val)
Insert helps us to add an element in between our list.
pos => takes the position number where we want to add the new element.
val => takes the value to be inserted.
extend()
extend helps us to add one list or other iterable object to other list.
Delete List Elements
With the help of below methods we can delete elements of a list.
pop()
pop will delete the last element from the list if no index number is passed.
pop(1)
We can delete the element of particular position with the help of pop by passing the index number.
remove()
-
We can delete the element with the help of remove by passing the value.
-
If the value specified is not present then it will throw an error.
del a[start:stop]
Delete can help us to delete more than one element by passing the slicing value.
del a
Complete list can be deleted if we just write the varaible name without any index number
clear()
Clear method help us to clear all the elements from the list. But variable is not deleted.
List Sort
List can be sort in ascending and descending order by using the sort method.
List Copy
List Loop
List Reverse
count()
index()
List Functions
List Comprehension
Suppose we want to create a list with numbers 1 to 10
-
As we can see that we write the above code in single line.
-
List comprehension is faster compared to traditional way.