Python | Assign range of elements to List
Assigning elements to list is a common problem and many varieties of it have been discussed in the previous articles. This particular article discusses the insertion of range of elements in the list. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using extend()
This can be solved using the extend function in which the insertion of range of numbers can be done on the rear end using the range function.
# Python3 code to demonstrate # Assigning range of elements to List # using extend() # initializing list test_list = [3, 5, 6, 8] # printing original list print("The original list : " + str(test_list)) # using extend() # Assigning range of elements to List test_list.extend(range(6)) # print result print("The list after adding range elements : " + str(test_list)) |
The original list : [3, 5, 6, 8] The list after adding range elements : [3, 5, 6, 8, 0, 1, 2, 3, 4, 5]
Method #2 Using * operator
This problem can also be solved using the * operator and with the advantage of flexibility of addition of elements at any position.
# Python3 code to demonstrate # Assigning range of elements to List # using * operator # initializing list test_list = [3, 5, 6, 8] # printing original list print("The original list : " + str(test_list)) # using * operator # Assigning range of elements to List res = [3, 5, *range(6), 6, 8] # print result print("The list after adding range elements : " + str(res)) |
The original list : [3, 5, 6, 8] The list after adding range elements : [3, 5, 0, 1, 2, 3, 4, 5, 6, 8]
Recommended Posts:
- Python | Print list elements in circular range
- Python | Assign ids to each unique value in a list
- Python | Assign value to unique number in list
- Python | Assign multiple variables with list values
- range() to a list in Python
- Python | Merge List with common elements in a List of Lists
- Python | Sorting list of lists with similar list elements
- Python | Add list elements with a multi-list based on index
- Python | Replace elements in second list with index of same element in first list
- Python | Numbers in a list within a given range
- Python | Maximum sum of elements of list in a list of lists
- Python | Indices of sorted list of list elements
- Python | Delete elements in range
- Python | Decimal step range in list
- Python | Alternate range slicing in list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



