List Operations in Python with Examples
Python List is a versatile data variable. It is a sequence in which elements are written as a list of comma-separated values between square brackets. It has the following syntax:
List_variable=[val1, val2,...]
Nested List
A nested List means that a list is within another list. It is a list that has elements of different data types which can include even a list.
Example:
list1= [1, 'a', 'abc', [2,3,4,5], 8,9] i=0 while i<(len(list1)): print("List1[",i,"]= ",list1[i]) i+=1
Output:
Cloning List
If you want to modify a list and it also keeps a copy of the original list, then you should create a separate copy of the list. It is called a Cloning List.
Example:
list1=[1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10] list2=list1 print("List1 =", list1) print("List2 =", list2) list3=list1[2:6] print("List3=", list3)
Output:
List Operations in Python
1. len: It returns the length of a list.
2. concatenation: It joins two lists.
3. repetition: It repeats elements in the list.
4. in: It checks if the value is present in the list.
5. not in: It checks if the value is not present in the list.
6. max: It returns the maximum value in the list.
7. Min: It returns the minimum value in the list.
8. sum: It adds the values in the list that have numbers.
9. all: It returns True if all elements of the list are true.
10. any: It returns True if any element of the list is true. If the list is empty, returns False.
11. list: It converts an iterable (tuple, string, set, dictionary) to a list.
12. Sorted: It returns a new sorted list. The original list isn’t sorted.