Python- Day 12- Working with Part of a List in Python
You learned how to access individual items in a list. Now, let’s see how to work with groups of items using slices.
Slicing a List:
A slice is a part of a list. To create a slice, specify the start and end index. Python stops just before the end index. For example:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
>>
['charles', 'martina', 'michael']
You can also select items from anywhere in the list:
print(players[1:4])
>>
['martina', 'michael', 'florence']
Omitting Start or End Index:
If you leave out the start index, Python starts from the beginning:
print(players[:4])
>>
['charles', 'martina', 'michael', 'florence']
If you omit the end index, it goes to the last item:
print(players[2:])
>>
['michael', 'florence', 'eli']
Using Negative Indices:
Negative numbers can select items from the end of the list. For example:
print(players[-3:])
>>
['michael', 'florence', 'eli']
Looping Through a Slice:
You can loop through a slice like this:
for player in players[:3]:
print(player.title())
This will print the first three players’ names with their first letters capitalized.
Copying a List:
To copy a list, use a slice without specifying any indices:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
Now, both my_foods
and friend_foods
contain the same items.
You can confirm they’re separate by adding new items:
my_foods.append('cannoli')
friend_foods.append('ice cream')
The lists are now different:
my_foods
:['pizza', 'falafel', 'carrot cake', 'cannoli']
friend_foods
:['pizza', 'falafel', 'carrot cake', 'ice cream']
Be Careful When Copying Without a Slice:
If you assign a list directly without slicing, like this:
friend_foods = my_foods
Both variables will point to the same list. Changes to one list will affect the other.
To avoid this, always use slicing ([:]
) when you need a separate copy of a list.
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!