Lists are very frequently used data container in Python. While using lists we may come across a situation where the elements of the list maybe a sequence of numbers. We can add this sequence of numbers to a list using many Python functions. In this article we will explore different ways of doing that.
With range and extend
The extent function allows us to increase the number of elements in a list. Will use the range function and apply extend to the list so that all the required sequence of numbers are added at the end of the list.
Example
listA = [55,91,3] # Given list print("Given list: ", listA) # Apply extend() listA.extend(range(4)) # print result print("The new list : ",listA)
Output
Running the above code gives us the following result −
Given list: [55, 91, 3] The new list : [55, 91, 3, 0, 1, 2, 3]
With * and range
The * operator can expand the list with the advantage of adding the elements at any position. We also use the range function again toward the sequence of numbers.
Example
listA = [55,91,3] # Given list print("Given list: ", listA) # Apply * Newlist = [55,91,*range(4),3] # print result print("The new list : ",Newlist)
Output
Running the above code gives us the following result −
Given list: [55, 91, 3] The new list : [55, 91, 0, 1, 2, 3, 3]