Posts: 1
Threads: 1
Joined: Feb 2024
I am trying to learn Python3 and have come across Lists. I know that counting begins at 0 and ends at -1
But i am having some difficulty in understanding the following example:
S[6:1:-2] = A B C D E F G H I
Could someone please explain what is going on here please.
Posts: 256
Threads: 60
Joined: Apr 2019
The following code should help you (do additional tests by yourself):
Alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# extract from 6th term to 1st one (excluded) every 2 terms ("-" means opposite sens i.e. from right to left)
Extract = Alphabet[6:1:-2]
print(f"Extract = {Extract}") Output: Extract = ['G', 'E', 'C']
Posts: 8,090
Threads: 154
Joined: Sep 2016
Feb-16-2024, 10:07 AM
(This post was last modified: Feb-16-2024, 10:07 AM by buran.)
(Feb-16-2024, 08:06 AM)Luchano55 Wrote: counting begins at 0 and ends at -1 That is not correct statement. The correct is that you can use both positive and negative indexes.
spam = list(range(10))
print(spam)
print(spam[:100])
print(spam[-1::-2])
print(spam[-5:]) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 7, 5, 3, 1]
[5, 6, 7, 8, 9]
(Feb-16-2024, 08:06 AM)Luchano55 Wrote: S[6:1:-2] = A B C D E F G H I
Could someone please explain what is going on here please.
Start from element at index 6, and go to element at index (not including) 1, using step -2, i.e. every other one
print(spam[6:1:-2]) Output: [6, 4, 2]
Posts: 6,221
Threads: 16
Joined: Feb 2020
Feb-16-2024, 01:26 PM
(This post was last modified: Feb-16-2024, 01:27 PM by deanhystad.)
This is not a valid python expression.
Quote:S[6:1:-2] = A B C D E F G H I
Was it supposed to be this?
S[6:1:-2] = A, B, C, D, E, F, G, H, I This is a valid expression, but there is an error. S[6:1:-2] is a slice consisting of S[6], S[4] and S[2]. You cannot assign A, B, C, D, E, F, G, H and I to a slice of length 3.
This is valid, assuming len(S) >6 and that A, B and C are initialized variables.
S[6:1:-2] = A, B, C
Posts: 832
Threads: 131
Joined: Jul 2017
Maybe this will help?
from string import ascii_lowercase, ascii_uppercase
# quick way to get the alphabet
alphabet = ascii_lowercase
# get every second letter, starting at alphabet[13]
# won't fetch alphabet[1]
myslice = alphabet[13:1:-2]
mylist = [i for i in alphabet]
# get every second letter, starting at mylist[13]
# won't fetch mylist[1]
mylistslice = mylist[13:1:-2]
|