w3resource

Python: Create a list by concatenating a given list which range goes from 1 to n

Python List: Exercise - 35 with Solution

Write a Python program to create a list by concatenating a given list with a range from 1 to n.

Python: Create a list by concatenating a given list which range goes from 1 to n

Sample Solution:

Python Code:

# Define a list 'my_list' containing elements 'p' and 'q'
my_list = ['p', 'q']

# Define a variable 'n' with the value 4
n = 4

# Use a list comprehension to create a new list 'new_list' by combining elements from 'my_list' with numbers from 1 to 'n'
new_list = ['{}{}'.format(x, y) for y in range(1, n+1) for x in my_list]

# Print the 'new_list' containing combinations of elements from 'my_list' and numbers
print(new_list)

Sample Output:

['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4'] 

Flowchart:

Flowchart: Create a list by concatenating a given list which range goes from 1 to n

Python Code Editor:

Previous: Write a Python program using Sieve of Eratosthenes method for computing primes upto a specified number.
Next: Write a Python program to get variable unique identification number or string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-35.php