Last modified: February 04, 2021 Show How to Append Multiple Items to List in PythonIn today's tutorial, we'll learn how to append multiple items to a list. Contents
1. Using the append() methodThe append() method adds a single element to an existing list. 1. iterate over the elements list. Let's see the example: my_list = ["DJANGO"] for i in ["PYTHON", "PHP"]: my_list.append(i) print(my_list)So, in the above code, we try to append ["PYTHON", "PHP"] to my_list by: 1. iterate over ["PYTHON", "PHP"]. output ['DJANGO', 'PYTHON', 'PHP']2. Using '+' operatorAnother way is using the '+' operator. my_list = ["DJANGO"] new_list = my_list + ["PYTHON", "PHP"] #print print(new_list)output ['DJANGO', 'PYTHON', 'PHP']3. Using extend() methodThe extend() method adds list elements to the current list. my_list = ["DJANGO"] #append to the list my_list.extend(["PYTHON", "PHP"]) #print print(my_list)output ['DJANGO', 'PYTHON', 'PHP']Real exampleNow, I'll give you an example in which we'll split a string into a list and append the list to an existing list. #my list my_list = ["DJANGO"] #my string my_string = "Hello PYTHON and PHP" #Split the String split_s = my_string.split(' ') #output ['Hello', 'PYTHON', 'and', 'PHP'] #append the result to my_list my_list.extend(split_s) print(my_list)output ['DJANGO', 'Hello', 'PYTHON', 'and', 'PHP']Related Posts:
Recent Tutorials:
Popular Tutorials:
|