'Using slice and get rid of the middle two numbers
This time I want to get the following result by using slice. However, I could not manage it. Is there a negative version of List[2:4] in this scenario?
Input:
List=[1,2,3,4,5,6,7]
Output:
List =[1,2,5,6,7]
Edited: By negative I mean that the I want this: List =[1,2,5,6,7] instead of this: List=[3,4]. I saw the answers and they work. Thank you very much but is there way to get the result by doing slicing?
Ps: I am not able to give votes due to my low level. Thank you for your understanding.
Solution 1:[1]
First off List[3:5] = [4, 5] so the "negative" version would be [1, 2, 3, 6, 7]. You can produce that with:
List[:3] + List[5:]
Solution 2:[2]
List[:3] + List[5:]
Hopefully that's not the real name of the variable ?
Solution 3:[3]
You can use del to remove part of a list specified by a slice:
xs = [1, 2, 3, 4, 5, 6, 7]
del xs[2:4]
print(xs)
# [1, 2, 5, 6, 7]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff |
| Solution 2 | Ji?í Baum |
| Solution 3 | Ji?í Baum |
