Question 6.10: Cutting Up a List You need to make a sublist of a list using......

Cutting Up a List

You need to make a sublist of a list using a range of the original list’s elements.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the [:] Python language construction. The following example returns a list containing the elements of the original list from index position 1 to index position 2 (the number after the : is exclusive):

>>> l = [“a”, “b”, “c”, “d”]
>>> l[1:3]
[‘b’, ‘c’]

Note that the character positions start at 0, so a position of 1 means the second character in the string and 5 means the sixth, but the character range is exclusive at the high end, so the letter d is not included in this example.

Discussion

The [:] notation is actually quite powerful. You can omit either argument, in which case the start or end of the list is assumed as appropriate. For example:

>>> l = [“a”, “b”, “c”, “d”]
>>> l[:3]
[‘a’, ‘b’, ‘c’]
>>> l[3:]
[‘d’]
>>>

You can also use negative indices to count back from the end of the list. The following example returns the last two elements in the list:

>>> l[-2:]
[‘c’, ‘d’]

Incidentally, l[:-2] returns [‘a’, ‘b’] in the preceding example.

See Also

All the recipes between Recipes 6.1 and 6.11 involve the use of lists.

See Recipe 5.15 where the same syntax is used for strings.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...