상세 컨텐츠

본문 제목

Sequence Slicing

Python

by techbard 2025. 3. 31. 19:32

본문

반응형
# Sequences are one of Python's most basic data structures.
# A sequence contains items arranged in order,
# and you can access each item using an integer index
# that represents its position in the sequence.

# Most sequence types also support an operation called slicing.
# And you can use this operation to access the subset of the items
# in a given sequence.

from collections import deque

names = ["Jim", "Pam", "Creed", "Michael", "Dwight", "Oscar", "Kevin", "Phyllis"]

# a slice is a subset of a sequence. The form is [start:stop:step]
print(names[1:3])

# using a step
print(names[::2])

# reversing with step of -1
print(names[::-1])

# get last one, two
print(names[-1]) # last one
print(names[-2:]) # last two

# not all sequence types support slicing, however

names_deque = deque(["Jim", "Pam", "Creed", "Michael", "Dwight", "Oscar", "Kevin", "Phyllis"])
# A deque is basically a double-ended queue
# and it's optimized for accessing elements from both ends.
# So this particular object supports most sequence operations.
for name in names_deque:
    print(name, " ", end='')

Jim  Pam  Creed  Michael  Dwight  Oscar  Kevin  Phyllis

print(names_deque[1:3]) # TypeError: sequence index must be integer, not 'slice'
반응형

관련글 더보기

댓글 영역