Home > Software engineering >  Defining a function for concatenation which works for strings and lists. How?
Defining a function for concatenation which works for strings and lists. How?

Time:10-27

I’m confused about why this can work for strings but not for lists. Does anyone have any suggestions as to why it might be?

def switcheroo(test):
    
    return test[1]   test[0]   test[2:]

CodePudding user response:

Although string and lists are both sequences, the interpretation of [] brackets varies depending on what expression is inside of them. If it's just a single integer value, then it used a the index of that element in the string or list, but when it the expression contains one or more : characters it's a slice and it evaluates to the specified subset of the original object — i.e. a substring or a sublist.

A way to write a function that handles both would be to restrict yourself to using slices:

def switcheroo(test):
#    return test[1]   test[0]   test[2:]
    return test[1:2]   test[0:1]   test[2:]


test1 = 'abcdef'
print(switcheroo(test1))  # -> bacdef

test2 = ['st','ack','over','flow']
print(switcheroo(test2))  # -> ['ack', 'st', 'over', 'flow']

CodePudding user response:

When test is a str any of the three - test[1] , test[0], and test[2:] are str. When test is a list, first two -test[1] and test[0] are str, but test[2:] is a list (even with one element). And as discussed in your other question, you cannot concatenate str and list.

Note, I say str, but they can be any type. I just know they are str from your other question.

  • Related