0
what is del()
a = [8, 0, 4, 6, 1] del(a[1::3]) print(sum(a)) why #output: 18
7 ответов
+ 4
del is short for delete.
1::3 means that from position one we delete every third element. So we delete 0 and 1.
Remaining: 18 in sum.
EDIT: Downvote? Seriously? 🤔
+ 1
Daniel Möhring, basically, the slice syntax is a shortcut for what you would write in a C-ish language with loop variables.
With the first number you set the start point, with the second number the (non-inclusive) end point, with the third the step width and direction. So by 10::-2 you'd move backwards from 10, skipping one.
Also by using negative numbers, you have a shortcut to count from the end of an iterable: -1 is the last element, -2 the second last and so on.
1 to 3 would simply be [1:4]. (If you think in C: (i=1; i<4; ++i))
+ 1
Daniel Möhring, in the beginning it may be confusing, but after you got used to the patterns, you can read them easily and don't want to miss them.
array[::2] # every even index
array[1::2] # every odd
array[::-1] # array backwards
array[:-3] # array without the
# two final elements
array[:] # shallow copy of
#a whole array
and so on.
Combine that with 'comprehensions' and you can often write in one line, what would be a whole block in C-ish languages.
0
*del is a tag which shows the deleted text. It is no longer supported in HTML5*
Its about python bro ;)
0
HonFu That seems kinda hard to read imo
I mean these short forms are propably easier to write but for understanding purpose you can get quite confused i think.