Let's take a Python list and then append the first list into the second list. Read the python question correctly and this is quite tricky. You have to append the first list to the second list.
Let's use both the list containing n integers and append it.
Note that appending a list to another list will create a nested list
Write A Python Script To Append A List To The Second List
This program can be divided into three parts: first is accept the first list, second is accept the second list, third is append the first list to the second list and print it.
First section: let's take a variable named length and ask a user to enter the list1 length. using the for loop iterate from 0 to list length and ask the user to enter all the items present in the list1. this will create a first list of numbers
length = int(input("Enter List1 Length : "))
list1 = []
for _ in range(length):
item = int(input("Enter Item to Add in List1 : "))
list1.append(item)
Second section: take the same variable length and ask user to enter the list to length, using the for loop iterate from 0 to second list length and accept the list items as numbers using the input function call and append it to the second list. this will create the second list containing numbers.
length = int(input("Enter List2 Length : "))
list2 = []
for _ in range(length):
item = int(input("Enter Item to Add in List2 : "))
list2.append(item)
Third section : Using the built-in function call append the list1 to the list2. Using the print function call print 1 user friendly message, use the for loop to iterate on the members of list2 and inside the for loop use print function call to print all the members of the second list.
list2.append(list1)
print("The contents of Second List after appending is : ")
for item in list2:
print(item)
Python Code
=====================
length = int(input("Enter List1 Length : "))
list1 = []
for _ in range(length):
item = int(input("Enter Item to Add in List1 : "))
list1.append(item)
length = int(input("Enter List2 Length : "))
list2 = []
for _ in range(length):
item = int(input("Enter Item to Add in List2 : "))
list2.append(item)
list2.append(list1)
print("The contents of Second List after appending is : ")
for item in list2:
print(item)
Output
===================
Enter List1 Length : 4
Enter Item to Add in List1 : 11
Enter Item to Add in List1 : 22
Enter Item to Add in List1 : 33
Enter Item to Add in List1 : 44
Enter List2 Length : 3
Enter Item to Add in List2 : 1
Enter Item to Add in List2 : 2
Enter Item to Add in List2 : 3
The contents of Second List after appending is :
1
2
3
[11, 22, 33, 44]
Conclusion
=====================
In the above output you can notice that the first list is getting appended to the second list and the second list turns out to be a nested list containing the first list as a Sub list.
Comment it down below if you have any suggestions to improve optimize the above Python program
0 Comments