How do I concatenate two lists using Python?
- User
How do I concatenate two lists using Python?
Assistant
Here are a few ways to concatenate (join) two lists in Python:
pythonlist1 = [1, 2, 3] list2 = [4, 5, 6] # Use the + operator list3 = list1 + list2 print(list3) # [1, 2, 3, 4, 5, 6] # Use the extend() method list1.extend(list2) print(list1) # [1, 2, 3, 4, 5, 6] # Use the append() method in loop for x in list2: list1.append(x) print(list1) # [1, 2, 3, 4, 5, 6] # Use list comprehension list3 = [y for x in (list1, list2) for y in x] print(list3) # [1, 2, 3, 4, 5, 6]The key things to note are:
- Using + or extend()/append() modifies the existing lists
- List comprehension or + creates a new list
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.