Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Assign range of elements to List in Python
Lists are very frequently used data containers in Python. While using lists, we may come across a situation where we need to add a sequence of numbers to an existing list. We can add this sequence of numbers to a list using several Python functions. In this article, we will explore different ways of doing that.
Using range() with extend()
The extend() function allows us to increase the number of elements in a list. We 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
numbers = [55, 91, 3]
# Given list
print("Given list:", numbers)
# Apply extend()
numbers.extend(range(4))
# print result
print("The new list:", numbers)
The output of the above code is ?
Given list: [55, 91, 3] The new list: [55, 91, 3, 0, 1, 2, 3]
Using * Operator with range()
The * operator can expand the list with the advantage of adding the elements at any position. We also use the range() function to generate the sequence of numbers ?
Example
numbers = [55, 91, 3]
# Given list
print("Given list:", numbers)
# Apply * operator to insert range in the middle
new_list = [55, 91, *range(4), 3]
# print result
print("The new list:", new_list)
The output of the above code is ?
Given list: [55, 91, 3] The new list: [55, 91, 0, 1, 2, 3, 3]
Using List Comprehension with range()
We can also use list comprehension to create a new list by combining existing elements with a range of numbers ?
Example
numbers = [55, 91, 3]
# Given list
print("Given list:", numbers)
# Using list comprehension
new_list = numbers + [i for i in range(4)]
# print result
print("The new list:", new_list)
The output of the above code is ?
Given list: [55, 91, 3] The new list: [55, 91, 3, 0, 1, 2, 3]
Comparison
| Method | Modifies Original List? | Position Control | Best For |
|---|---|---|---|
extend() |
Yes | End only | Appending to existing list |
* operator |
No (creates new) | Any position | Inserting at specific positions |
| List comprehension | No (creates new) | End only | Functional programming style |
Conclusion
Use extend() when you want to modify the original list by adding elements at the end. Use the * operator when you need to insert elements at specific positions while creating a new list.
