Wednesday 24 January 2024

List replication using * operator in Python

The * operator can be applied between a list and an integer, to duplicate the list the specified number of times.

Syntax

list * no_of_times_to_replicate
>>> numbers = [1, 2, 3, 4]
>>> numbers_twice = numbers * 2
>>> numbers_thrice = numbers * 3
>>> 
>>> numbers
[1, 2, 3, 4]
>>> 
>>> numbers_twice
[1, 2, 3, 4, 1, 2, 3, 4]
>>> 
>>> numbers_thrice
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

Above snippet demonstrates the use of the * operator for list replication.

 

numbers = [1, 2, 3, 4]

This line creates a list named numbers containing the elements 1, 2, 3, and 4.

 

numbers_twice = numbers * 2

This line replicates the numbers list two times. The * operator, when used with a list and an integer, creates a new list by repeating the original list the number of times specified by the integer. Here, numbers * 2 results in [1, 2, 3, 4, 1, 2, 3, 4]. The list numbers is repeated twice, and this new list is assigned to the variable numbers_twice.

 

numbers_thrice = numbers * 3

Similarly, this line replicates the numbers list three times. The expression numbers * 3 produces [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]. The original list is repeated three times, and this new concatenated list is stored in the variable numbers_thrice.

 

In summary, the * operator is used to create larger lists by repeating the contents of an existing list a specified number of times. This snippet demonstrates creating two new lists, one with the elements of the original list repeated twice and the other repeated thrice.


Previous                                                 Next                                                 Home

No comments:

Post a Comment