link Go
link Go

Reputation: 13

Why cant I and how can I concatenate a string to sliced list with python?

Im trying the next code:

lst = [1,2,3, "hi", 5]
string = "bye"
print lst[3:4].append(string)

By hoping get the next output:

["hi", "bye"]

But what I get is the:

None

output

Why cant I do this such of thing? Do I have to save the list to an object before im concatenating any object to it? Why its not like in CPP that the object returned on the place?

Upvotes: 0

Views: 35

Answers (1)

javidcf
javidcf

Reputation: 59731

lst[3:4] is giving you ["hi"], and .append(string) is appending the string to that list, but the return value of append is None. You can do one of the following:

lst = [1,2,3, "hi", 5]
string = "bye"
lst2 = lst[3:4]
lst2.append(string)
print lst2

Or:

lst = [1,2,3, "hi", 5]
string = "bye"
print lst[3:4] + [string]

Upvotes: 2

Related Questions