Created
June 28, 2022 05:10
-
-
Save Abdurahman-hassan/148be85d873c76bc9f66362404beffdc to your computer and use it in GitHub Desktop.
a slicing description in Python with a simple examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# a list from 0 to 6 | |
piano_keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] | |
print(piano_keys[1:5]) | |
# will print from position 1 to the position 5 | |
# ['b', 'c', 'd', 'e'] | |
print(piano_keys[1:5:2]) | |
# will print from position 1 to the position 5 | |
# it will skip the first one after position 1 and print the second one only one time | |
# ['b', 'd'] | |
print(piano_keys[1:]) | |
# will print from position 1 to the end | |
# ['b', 'c', 'd', 'e', 'f', 'g'] | |
print(piano_keys[:5]) | |
# will print from the start to position 5 | |
# ['a', 'b', 'c', 'd', 'e'] | |
print(piano_keys[::2]) | |
# it will skip the first one and print the second one until the list ends | |
# ['a', 'c', 'e', 'g'] | |
print(piano_keys[::-1]) | |
# it will reverse the list | |
# ['g', 'f', 'e', 'd', 'c', 'b', 'a'] | |
# a slicing works with tuples also | |
# a tuples from 0 to 6 | |
piano_keys_in_tuples = ('a', 'b', 'c', 'd', 'e', 'f', 'g') | |
print(piano_keys_in_tuples[::-1]) | |
# it will reverse the list | |
# ('g', 'f', 'e', 'd', 'c', 'b', 'a') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment