Slicing lists in Python
List slicing in Python allows you to extract a portion of a list using the colon (:
) operator. The syntax for slicing is my_list[start:stop:step]
, where start
is the index to begin the slice, stop
is the index to end the slice (exclusive), and step
determines the interval between elements. All sections are optional, allowing various slicing techniques like omitting indices or using negative indices to count from the end of the list.
Example code:
def split_players_into_teams(players):
team_even = players[::2] # Players at even indexes (0, 2, 4, ...)
team_odd = players[1::2] # Players at odd indexes (1, 3, 5, ...)
return team_even, team_odd
How does this work?
set the stage
def split_players_into_teams(players):
Here, you are creating a function called split_players_into_teams
and the input in this case happens to be a list of players from elsewhere called players
. So what are we going to do with these player names?
divvy the items in the list
Our goal into this is to separate into odd and even teams. We do that in this section:
team_even = players[::2]
team_odd = players[1::2]
with
team_even = players[::2]
we are not designating a start, so it starts at 0, the first entry (the first :
). It has no end (the second :
) and jumps every 2
positions. These are obviously slicing the evens into a list called team_even
.
with
team_odd = players[1::2]
now we are doing the same mechanism we did previously, but now with the first 1
, we’ve shifted the positioning of the list, which makes all of the results now odd. They go, as expected, into team_odd
.
present the results
Now that we have the players broken into lists (this could be any kinds of items in your use case) we need to return that. Easy peasy:
return team_even, team_odd
We are done, and you have two divided lists to work with.