Can list slicing work without specifying the end?

Question

In this exercise, the list slice shows a start and end point. Will a slice work without specifying the end?

Answer

Yes, it is possible to use a slice without specifying the end. In that case, the slice will return the list from the start point through the end of the list. This would be useful if you wanted to remove a known number of items from the start of the list and keep the remainder.

In the following example code, a list is sliced using a defined start and end point and then again specifying only the start.

colors = ['red', 'green', 'blue', 'yellow', 'orange']

# Values from index 1 to less than 4 = ['green', 'blue', 'yellow']
print(colors[1:4])

#  Start at index 1 till end = ['green', 'blue', 'yellow', 'orange']
print(colors[1:])
15 Likes

From the exercise, if we use employees.append( ) to add a name to the list, can we select the 8th element in the list?

employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert']

employees.append('Carlos')

print(employees(8))
2 Likes

Hey @cesararellano7696287, welcome to the forums!

A couple things you might want to remember are:

To select an element of a list, you use square brackets() instead of parentheses(). So if you were going to do this, you would have to change that.


employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert']
                 ^          ^       ^       ^      ^       ^        ^  
                0th        1st     2nd     3rd    4th     5th      6th
employees.append('Carlos')

If you added the list item ‘Carlos’ to the end of the list, that new element would be at list index 7 so this code would give you an error regardless.

Hope this helps!
Steven

4 Likes

Hi Steven,

Thank you so much. That’s what I figured would be the case. Appreciate the clarification.

Thanks,

Cesar

1 Like
employees += "john"
['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert', 'carlos', 'j', 'o', 'h', 'n']

I added in carlos using append as discussed above, then tried to use += and it separates the letters in john.  Not sure what is different?  Thanks

Hi @core1805653314,

The string, "john", was converted to a list of its component characters in order for it to be concatenated to the list of employees. Try placing "john" within its own list, instead, in order to perform the concatenation, as follows:

employees += ["john"]
7 Likes