How to Concatenate, Repeat, and Determine the Length of Lists
How can we combine two or more lists or repeat the contents of a list?
In Python, you can use the addition operator (+) to combine lists and the multiplication operator (*) to repeat them.
You can also use the len() function to find the length of a list.
Concatenating Lists
You can combine two lists by using the + operator.
fruits = ["apple", "banana"]
vegetables = ["carrot", "tomato"]
combined_list = fruits + vegetables
# ["apple", "banana", "carrot", "tomato"]
print("combined_list:", combined_list)
In the example above, the fruits and vegetables lists are combined using the + operator and stored in the combined_list.
Repeating Lists
The * operator repeats the elements of a list a specified number of times.
fruits = ["apple", "banana"]
repeated_fruits = fruits * 2
# ["apple", "banana", "apple", "banana"]
print("repeated_fruits:", repeated_fruits)
In the example above, elements of the fruits list are repeated twice using the * operator and stored in repeated_fruits.
Determining the Length of a List
The len() function returns the number of elements that a list contains.
fruits = ["apple", "banana"]
length = len(fruits) # Store the length of list fruits in variable length
print("length:", length) # 2
Since there are two elements in the fruits list, the result of len(fruits) is 2.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.