Concatenation (+) and Repetition (*) in Python

Learn about concatenation and repetition operators supported by Python sequence data types.

Photo by Rishab Lamichhane on Unsplash

Concatenation and Repetition in Python:

In python, concatenations and repetitions are supported by sequence data types both mutable(list) and immutable(tuple, strings). Sequence types like range objects do not support concatenation and repetition. Furthermore, Python containers that are non-sequence data types (such as sets or dictionaries) do not support concatenation and repetition operators. In this article, we will take a detailed look at concatenations and repetitions that are supported by sequence data types such as list, tuple, and strings.


Topics covered in this story:

Photo by Author

Concatenation:

Concatenation is done by + operator. Concatenation is supported by sequence data types(string, list, tuple). Concatenation is done between the same data types only.

Syntax:

a+b

String Concatenation:

The string is an immutable sequence data type. Concatenating immutable sequence data types always results in a new object.

Example 1: Strings are concatenated as they are, and no space is added between the strings.

s1="Welcome"
s2="to"
s3="python"
s4=s1+s2+s3
print (s4)#Output:Welcometopython

Example 2: If we want space between two strings while concatenating, we either have to include a space in the string itself or concatenate the space.

Method 1:

s1="Welcome "
s2="to "
s3="python"
s4=s1+s2+s3
print (s4)#Output:Welcome to python

Method 2:

s1="Welcome"
s2="to"
s3="python"
s4=s1+" " + s2+" "+ s3
print (s4)#Output:Welcome to python

Example 3: Concatenation between different data types.

This will raise TypeError.

s1="Welcome"
s2="to"
s3="python"
s4=[3.8]
s5=s1+s2+s3+s4
#Output:TypeError: can only concatenate str (not "list") to str

Example 4:Using + operator results in and addition to int objects and concatenation in strings.

s=1+2
print (s)#Output:3
print (type(s))#Output:<class 'int'>
s1='1'+'2'
print (s1)#Output:12
print (type(s1))#Output:<class 'str'>

Example 5: If the strings are placed next to each other without + operator this will result in a concatenation.

s='Welcome''to''Python'
print (s)#Output:WelcometoPython
s1='Welcome'+'to'+'Python'
print (s)#Output:WelcometoPython

Example 6: Apply methods to strings while concatenating.

s1="Welcome"
s2="TO"
s3="Python"
s4=s1+s2.lower()+s3
print (s4)#Output:WelcometoPython

Concatenating tuple objects:

The tuple is an immutable sequence data type. Concatenating immutable sequence data types always results in a new object.

Example 1: Concatenating two tuple objects

t1=(1,2)
t2=(3,4)
print (t1+t2)
#Output:(1, 2, 3, 4)

Example 2: Concatenating between different data types

t1=(1,2)
t2=[3,4]
print (t1+t2)
#Output:TypeError: can only concatenate tuple (not "list") to tuple

Concatenating list objects:

Example 1: Concatenating two list objects

l1=[1,2]
l2=[3,4]
print (l1+l2)
#Output:[1, 2, 3, 4]

Example 2: Applying sorted() functions to list while concatenating

l1=[1,2]
l2=[5,3,4]
print (l1+sorted(l2))
#Output:[1, 2, 3, 4, 5]

The difference between concatenating lists and calling extend method in the list:

Concatenating two lists will result in a new list object, but calling extend method will update the original list itself. Its return type is None.

l1=[1,2]
l2=[3,4]
l3=l1+l2
print (l3)#Output:[1,2,3,4]
l1=[1,2]
l2=[3,4]
print (l1.extend(l2))#Output:None
print (l1)#Output:[1,2,3,4]

Concatenation not supported by set and dictionary.

This will raise TypeError.

l1={1,2}
l2={3,4}
#print (l1+(l2))
#Output:TypeError: unsupported operand type(s) for +: 'set' and 'set'
d1={'1':'a','2':'b'}
d2={'3':'c'}
print (d1+d2)
#Output:TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

Repetition:

Sequences datatypes (both mutable and immutable) support a repetition operator * The repetition operator * will make multiple copies of that particular object and combines them together. When * is used with an integer it performs multiplication but with list, tuple or strings it performs a repetition

Syntax:

a*b

Example 1: Repetition operator on Strings

s1="python"
print (s1*3)
#Output:pythonpythonpython

Example 2: Repetition operator on List

Items in the sequences are not copied but are referenced multiple times.

l1=[1,2,3]
print (l1 * 3)
#Output:[1, 2, 3, 1, 2, 3, 1, 2, 3]

Example 3: Repetition operator on a nested list

Items in the sequences are not copied, they are referenced multiple times.
l1=[[2]]
l2=l1*2

Elements in list l2 are referring to the same element in list l1. So, modifying any of the elements of list l1 will modify list l2 as well.

l1=[[2]]
l2=l1*2
print (l2)#Output:[[2], [2]]
l1[0][0]=99
print (l1)#Output:[[99]]
print (l2)#Output:[[99], [99]]
Photo by Author

Example 4: Repetition operator on a tuple object

t=(1,2)
print (t*3)#Output:(1, 2, 1, 2, 1, 2)

Example 5: Repetition value is given as 0.

When a value less than or equal to 0 is given, it will return an empty sequence of the same type.

l1=[1,2,3]
print (l1 * 0)#Output:[]
t=(1,2)
print (t*0)#Output:()

Example 6: * operator on int object

It will perform the multiplication operation for int object.

print (2*3)#Output:6

Example 7:Repetition operator on set and dictionary object

It will raise TypeError.

s1={1,2}
#print (s1*2)
#Output:TypeError: unsupported operand type(s) for *: 'set' and 'int'
d1={'a':1}
print (d1*2)
#Output:TypeError: unsupported operand type(s) for *: 'dict' and 'int'

Repetition operator vs repeat() function

Repeat()
This makes an iterator that returns object over again and again, and runs indefinitely unless the times argument is mentioned. If the times argument is not mentioned, it will return an infinite iterator. Set, dictionary , and data types are also supported in repeat() function. This method is supported by the itertools module.

import itertools
#dict is used as an argument
l1=itertools.repeat({'a':1},times=3)
print (list(l1))
#string is used as an argument.times argument is mentioned as 10.It will repeat the string 10 times.
l2=itertools.repeat("hello",times=3)
print (list(l2))#Output:['hello', 'hello', 'hello']
#list is used as argument
l3=itertools.repeat([1,2],times=2)
print (list(l3))#Output:[[1, 2], [1, 2]]
#tuple is used as an argument
l4=itertools.repeat(('red','blue'),times=2)
print (list(l4))#Output:[('red', 'blue'), ('red', 'blue')]
#set is used as an argument
l5=itertools.repeat({1,2},times=2)
print (list(l5))#Output:[{1, 2}, {1, 2}]

Conclusion:

The concatenation and repetition operators are supported only by sequence datatypes except for when a range object is present. Both concatenation and repetition always result in a new object. Concatenation is done only between the same datatypes, and the difference between the concatenating list and the extend method is that concatenation results in a new list object where extend() will update the original list. Repetition can also be performed by using a repeat() method and this will return an iterator. Set and dictionary data types also supported in repeat() function.

I hope that you have found this article helpful, thanks for reading!


Resources:

https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s