How to Concatenate, Repeat, and Determine the Length of Lists
How can we concatenate two or more lists or repeat the contents of a list?
In Python, you can use the addition operator (+)
to concatenate 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 concatenate 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 concatenated 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 2 elements in the fruits
list, the result of len(fruits)
is 2.
Which of the following is a method to repeat a list three times?
list + 3
list - 3
list * 3
len(list) * 3
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result