Lists containing values of any data type can be stored in containers called Python lists. A list is a grouping of elements from any data type, to put it simply.
list1 = [‘harry’, ‘ram’, ‘Aakash’, ‘shyam’, 5, 4.85]
Strings, an integer, and even a float element are included in the list above. Any type of data can be included in a list; a list need not be created using only one data type. Any type of data can be included in the list.
Indices can also be used to access list elements; for example, the first element of a list has an index of 0, the second element has an index of 1, and so on.
An error will be returned if you enter an index that isn’t present in the list. For example, list1[4] will generate an error if list1 has four members since the list index ranges from 0 to (index-1) or 3.
[] # list with no member, empty list
[1, 2, 3] # list of integers
[1, 2.5, 3.7, 9] # list of numbers (integers and floating point)
[‘a’, ‘b’, ‘c’] # list of characters
[‘a’, 1, ‘b’, 3.5, ‘zero’] # list of mixed value types
[‘One’, ‘Two’, ‘Three’] # list of strings
List Methods:
This is a list of Python’s list methods. Any Python list can utilize these methods to generate the appropriate output.
# List Methods :
l1=[1,8,4,3,15,20,25,89,65] #l1 is a list
print(l1)
l1.sort()
print(l1) #l1 after sorting
l1.reverse()
print(l1) #l1 after reversing all elements
List slices
List slices and string slices both return a portion of the list that was retrieved from the source. you can make list slices using the following structure by using indices to access elements:
seq = list1[start_index:stop_index]
licing will go from a start index to stop_index-1. The seq list, a slice of list1, contains elements from the specified start_index to specified (stop_index – 1).
When utilizing lists in Python, there are numerous list methods that simplify our lives. Here are a few of them for your consideration.
list1=[1,2,3,6,,5,4] #list1 is a list
list1.append(7) # This will add 7 in the last of list
list1.insert(3,8) # This will add 8 at 3 index in list
list1.remove(1) #This will remove 1 from the list
list1.pop(2) #This will delete and return index 2 value.