Concatenating Sequence Types
Concatenation is the process of combining two or more sequence types in Python. This is a common operation when working with data and is often used to create larger sequences from smaller ones.
Concatenating Strings
You can concatenate strings using the +
operator. This allows you to combine multiple strings into a single string.
Example:
greeting = "Hello, " + "LabEx!"
print(greeting) ## Output: "Hello, LabEx!"
Concatenating Lists
You can concatenate lists using the +
operator. This creates a new list that contains all the elements from the original lists.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) ## Output: [1, 2, 3, 4, 5, 6]
Concatenating Tuples
Similar to lists, you can concatenate tuples using the +
operator. This creates a new tuple that contains all the elements from the original tuples.
Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) ## Output: (1, 2, 3, 4, 5, 6)
Concatenating Ranges
Concatenating ranges is not a common operation, as ranges are typically used for iteration or indexing. However, you can convert a range to a list and then concatenate the lists.
Example:
range1 = range(1, 4)
range2 = range(4, 7)
combined_list = list(range1) + list(range2)
print(combined_list) ## Output: [1, 2, 3, 4, 5, 6]
By understanding how to concatenate different sequence types in Python, you can effectively combine and manipulate data to meet your programming needs.