What are Lists in Python?
Lists are ordered sequences of objects, they use squarebrackets and comma(,) to separate elements in them. These are very frequently used data structures to hold multiple items/objects in Python. A list can contain objects of different types like ., strings and numbers.
Lists are the same as strings. with all accessing types and methods.
The built-in(len) method is used to find the length of the list.
Each character in the list is called as Element. These Elements in lists can be accessed using indexes.
We can slice to create new lists from existing lists.
my_list=[1,3,5,6] #6 ( len(my_list)-1 evaluates 3 elm=my_list[len(my_list)-1] #my_list means element at index 3 print(elm) #6 #index 3 evaluates 6
Manipulating Lists in Python
In lists, we can update the elements. what we want to change. Python lists are dynamic in nature this means they can grow and shrink I size as needed. we can append(add) elements to the end of the lists using the append() method and we can remove elements using the pop() method.
my_list=[1,2,3,4] my_list.append(5) #[1,2,3,4,5] my_list.pop(2) #[1,3,4,5]
Sorting Lists in Python
Lists can be sorted(arrangement in ascending order) using the sort() method, this method modifies the list inplace so that it's sorted numbers as well as strings.
num_list=[2,5,3,7,100,11] num_list.sort() #[2,3,5,7,11,100] string_list=['all','dogs','are','really','cute'] string_list.sort() #['all','are','cute','dogs','really']
If we want to sorted in descending order we use ( (variable_name).sort.reverse ) (or) ( (variable_name).sort(reverse=true) ) mostly 2ndsyntax is preferable because its a parameter performing with one operation only..
Reversing a Lists in Python
We can reverse a list using ( string_list.reverse() ).
list1 = [1, 9, 6, 4, 1, 2, 8] list1.reverse() print(list1) #[8, 2, 1, 4, 6, 9, 1] list2 = ['p', 'r', 'a', 'h', 'l', 'a', 'd'] list2.reverse() print(list2) #['d', 'a', 'l', 'h', 'a', 'r', 'p']