Can you index a list of strings in Python?


The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

Python Lists

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values [items] between square brackets. Important thing about a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −

list1[0]: physics list2[1:5]: [2, 3, 4, 5]

Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append[] method. For example −

#!/usr/bin/python list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2] list[2] = 2001; print "New value available at index 2 : " print list[2]

Note − append[] method is discussed in subsequent section.

When the above code is executed, it produces the following result −

Value available at index 2 : 1997 New value available at index 2 : 2001

Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which element[s] you are deleting or the remove[] method if you do not know. For example −

#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; print list1 del list1[2]; print "After deleting value at index 2 : " print list1

When the above code is executed, it produces following result −

['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000]

Note − remove[] method is discussed in subsequent section.

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

Python Expression Results Description
len[[1, 2, 3]] 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

Assuming following input −

L = ['spam', 'Spam', 'SPAM!'] Python Expression Results Description
L[2] SPAM! Offsets start at zero
L[-2] Spam Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods

Python includes the following list functions −

Sr.No. Function with Description
1 cmp[list1, list2]

Compares elements of both lists.

2 len[list]

Gives the total length of the list.

3 max[list]

Returns item from the list with max value.

4 min[list]

Returns item from the list with min value.

5 list[seq]

Converts a tuple into list.

Python includes following list methods

How can I extract the index of a substring in a python list of strings [preferentially in a rapid way to handle long lists]?

For example, with mylist = ['abc', 'day', 'ghi'] and character 'a', I would like to return [0, 1, -1].

0

In this lesson, you’ll see how to access individual elements and sequences of objects within your lists. Lists elements can be accessed using a numerical index in square brackets:

This is the same technique that is used to access individual characters in a string. List indexing is also zero-based:

>>>>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[0] 'spam' >>> a[2] 'bacon' >>> a[5] 'lobster' >>> a[len[a]-1] 'lobster' >>> a[6] Traceback [most recent call last]: File "", line 1, in a[6] IndexError: list index out of range

List elements can also be accessed using a negative list index, which counts from the end of the list:

>>>>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[-1] 'lobster' >>> a[-2] 'ham' >>> a[-5] 'egg' >>> a[-6] 'spam' >>> a[-len[a]] 'spam' >>> a[-8] Traceback [most recent call last]: File "", line 1, in a[-8] IndexError: list index out of range

Slicing is indexing syntax that extracts a portion from a list. If a is a list, then a[m:n] returns the portion of a:

  • Starting with postion m
  • Up to but not including n
  • Negative indexing can also be used

Here’s an example:

>>>>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[2:5] ['bacon', 'tomato', 'ham'] >>> a[-5:-2] ['egg', 'bacon', 'tomato'] >>> a[1:4] ['egg', 'bacon', 'tomato'] >>> a[-5:-2] == a[1:4] True

Omitting the first and/or last index:

  • Omitting the first index a[:n] starts the slice at the beginning of the list.
  • Omitting the last index a[m:] extends the slice from the first index m to the end of the list.
  • Omitting both indexes a[:] returns a copy of the entire list, but unlike with a string, it’s a copy, not a reference to the same object.

Here’s an example:

>>>>>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[:4] ['spam', 'egg', 'bacon', 'tomato'] >>> a[0:4] ['spam', 'egg', 'bacon', 'tomato'] >>> a[2:] ['bacon', 'tomato', 'ham', 'lobster'] >>> a[2:len[a]] ['bacon', 'tomato', 'ham', 'lobster'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[:] ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a == a[:] True >>> a is a[:] False >>> s = 'mybacon' >>> s[:] 'mybacon' >>> s == s[:] True >>> s is s[:] True

A stride can be added to your slice notation. Using an additional : and a third index designates a stride [also called a step] in your slice notation. The stride can be either postive or negative:

>>>>>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[0:6:2] ['spam', 'bacon', 'ham'] >>> a[1:6:2] ['egg', 'tomato', 'lobster'] >>> a[6:0:-2] ['lobster', 'tomato', 'egg'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[::-1] ['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

00:00 In this video, you’ll practice list indexing and slicing. The elements of a list can be accessed by an index. To do that, you name the list, and then inside of a pair of square brackets you use an index number, like what I’m showing right here.

00:17 That allows access to individual elements within the list. The indexing for the list is zero-based. So if you have a list such as this, with these six elements, the indices start with 0 and would go up to 5.

00:36 Let me have you try that out. Start with a new list.

00:47 Here’s a. As described, indexes are zero-based for lists, so a[0] would access the first item in that list.

01:03 a[2] would access the third one. And in this case, a[5] would access the last. Another way to get there would be a and the len[] [length] of a minus 1.

01:18 If you use an index value that’s too high, Python will raise an exception—an IndexError saying that the list index is out of range. Negative indexing is available also.

01:33 If you want to access the last item, you’d start with -1. So continuing to work with that list a I’ll have you try out negative indexing.

01:44 a[-1] will access the last item, a[-2], and so forth. So in this case -6—which is also negative the length of your list—would return the first item.

02:05 If you try to access an index that’s beyond the scope, you’ll get that index out of range also. Slicing is available too. Slicing’s an indexing syntax that’s going to extract a portion from your list. So in this example, if a is your list, then inside your square brackets you would have your two index numbers separated by a colon [:], and it’s going to return a portion of that a list that will start with position m and go up to but not include index n.

02:38 Using that same example from before, if you took a[2:5], you’d get the three objects in the middle, starting at index 2 and going up to index 4, but not including 5.

02:50 Let me have you try it out. Okay, so here’s your list. What if you wanted to slice? Let me have you start at index 2 and then using a colon. For the second index, use 5. From 2 up to but not including 5.

03:05 Great! You can also use negative indexes, so you could say starting at -5 and going to -2, which is the same as going from 1 to 4.

03:19 And you can confirm that here

03:25 as being True.

03:29 A shorthand is available. By omitting the first index, your slice is going to start at the beginning of the list and go up to the second index. If you omit the last index, it’s going to extend the slice from the first index and go all the way to the end of the list. And if you were to omit both indexes, it’s going to return a copy of the entire list.

03:54 And unlike with a string, it’s a copy—not a reference to the same object. So, what if you were to omit the first index? In that case, it will start at the beginning and go up to but not include that index. The same as from 0 to 4.

04:12 And in the same way, removing the second index will go all the way to the end, starting with this index up to the end. Here, you can use len[], which will return a value of 6, and if we go from 2 up to but not include 6, as the index.

04:35 If you were to remove both indexes and just have a [:], it returns the entire list. You can try this out by seeing if it is equal to a, which is True. But this is a copy and not a reference, whereas if you tried a is a[:]—it’s a copy.

05:01 It’s not a reference to the original. That could be confusing because if you’ve worked with strings before, if you have a string, s, which is 'mybacon', using the syntax of just the [:] does return the entire string.

05:20 What’s interesting about it is not only is s == s with the colon-only index, but it also is a reference to that object. Whereas with a list, it returns an entirely new object.

05:37 It’s possible to add a third index after the additional colon. That third index indicates a stride, but it’s also sometimes called a step. So in this example, if you had a slice that went from 0 to 6, with a step of 2, you would return the objects at index 0, 2, and 4—'spam', 'bacon', and 'ham'.

06:02 So if you went from index 0 up to 6 with a stride of 2, you’ll see it grab the first, third, and the fifth items, skipping over with a stride of two.

06:14 If you started that at 1 instead, you’d get the other three.

06:20 And it is possible to have a negative stride, though you’d put the first index in as the highest value, and then where you want to go up to, a 0, and in this case it’s going to go to -2.

06:36 In fact, a simple syntax for just simply reversing your list is to leave the first two indexes blank with a colon, and then the second colon and a -1—that will reverse your list.

06:50 Next, you’re going to practice using operators and some of Python’s built-in functions on your list.

Video liên quan

Chủ Đề