Thursday, October 11, 2018

More with Python lists

We know how to work through all the elements in a list. In Python it is also possible to work with a specific group of items in a list, which Python calls a slice. Slices are very useful in a number of situations. For instance, when you’re creating a game, you could add a player’s final score to a list every time that player finishes playing. You could then get a player’s top three scores by sorting
the list in decreasing order and taking a slice that includes just the first three scores.

When you’re working with data, you can use slices to process your data in chunks of a specific size. Or, when you’re building a web application,you could use slices to display information in a series of pages with an appropriate amount of information on each page.

How to make a slice

In order to make a slice just specify the index of the first and last elements you want to work with. As with the range() function, Python stops one item before the second index you specify. Thus to output the first three elements in a list, you would request indices 0 through 3, which would return elements
0, 1, and 2.

Let's print the first three entries  from our motorbikes list.

motorbikes = ['Honda','Yamaha','Suzuki','Royal Enfield', 'Harley Davidson']

print(motorbikes[0:3])


See the screenshot below for the program and output-



As seen in the screenshot above the output retains the structure of the list and includes the first three bikes in the list.

Using a slice we can generate any subset of a list. For example, if you want the second,third, and fourth items in a list, you would start the slice at index 1 and end at index 4.

print(motorbikes[1:4])

See the screenshot below for the program and output-



In case if we omit the first index in a slice, Python automatically starts your slice at the beginning of the list. So if our code says -

print(motorbikes[0:3])

First three elements of the motorbikes list will be printed. See the screenshot below for the program and output-

 

 If we want our slice to include the end of the list we can omit the last index in the code. So if we want to print the items from second item in our motorbikes list to the last item, we can write the slice as follows -

print(motorbikes[1:])

See the screenshot below for the program and output-



We can output any slice from the end of a list using negative index as we know a negative index returns an element a certain distance from the end of a list. Thus to print the last 3 items from our motorbikes list, we can write the slice as follows -

print(motorbikes[-3:])

See the screenshot below for the program and output- 

 

How to do looping through a slice


Looping through a slice is similar to looping done through lists. Hence in a for loop if we want to loop through a subset of the elements in a list, we use a slice.

Example: If we want to sell the first three bikes I own I'll use the slice as shown below -

for bike in motorbikes[0:3]:
   
    print(bike)


See the screenshot below for the program and output-


 

Slice allowed us to loop through the required items (first three bikes) in the last rather than looping through the entire list. Then the print statement printed the items.

How to copy a list using slice

If we want to use an existing list and make an entirely new list based on the first one, we can use a slice. Make a slice that includes the entire original list by omitting the first index and the second index ([:]). This tells Python to make a slice that starts at the first item and ends with the last item, producing a copy of the entire list.

For example, I own motorbikes which are stored in motorbikes list. Now I want to sell my motorbikes and keep the updated list as well as my list showing my total motorbikes. So I start with making a copy of motorbikes list, motorbikes_for_sale list which initially will contain the same items as the motorbikes list. The syntax to copy list is shown below-

motorbikes_for_sale = motorbikes[:]

See the screenshot below for the program and output-


 As seen in the output, both the lists contain same elements. Now I bought a new bike 'Enticer' and as it is a new one I'll not sell it in near future. So now my motorbikes list will be modified as 'Enticer' will be appended to the list.

motorbikes.append('Enticer')

See the screenshot below for the program and output-




From the above output we verified that motorbikes and motorbikes_for_sale are two different lists.

Now if I sell the bike I bought first , I can delete from my motorbikes_for_sale list, keeping my original motorbikes list unchanged for future references.

del motorbikes_for_sale[0]

See the screenshot below for the program and output-



Remember if we use del to delete an element, then it is deleted forever. Thus I'd advise you to modify this program and use remove() to remove a bike from the list and print the name of the removed bike.
If you have read my previous posts you should be able to do this.

Keep practicing and remember Python is easy to learn!




Share:

0 comments:

Post a Comment