Noob_? = Slicing individual elements of a list of strings

Last_names = ['Anderson', 'Smith', 'Rodriguez', 'Gonzalez', 'Horowitz', 'Keifer']
for x in Last_names:
	print(Last_names[0][:6])

I’m trying to figure out how to increase the [0] in the print function by one each time the loop runs so it moves to the next index point and will display the first 5 characters of all the last names in the list.

I’ve tried ‘i += 1’ before and after the print function but is gives an error.

do you mean,

last_names = ['Anderson', 'Smith', 'Rodriguez', 'Gonzalez', 'Horowitz', 'Keifer']
for x in last_names:
	print(x[:5])

or,

[x[:5] for x in ['Anderson', 'Smith', 'Rodriguez', 'Gonzalez', 'Horowitz', 'Keifer']]

if you want to skip index, could use enumerate,

[name[:5] for idx, name in enumerate(['Anderson', 'Smith', 'Rodriguez', \
'Gonzalez', 'Horowitz', 'Keifer']) if idx % 2 == 1]

or,

import itertools
[last_name[:5] for idx, (first_name, last_name) in \
enumerate(itertools.pairwise(['Anderson', 'Smith', 'Rodriguez', \
'Gonzalez', 'Horowitz', 'Keifer'])) if idx % 2 == 0]

The for: automatically iterates through the x items in your last_names list, handing out one item on each pass through the loop, so you don’t need any extra code to index through the list items. (I’m guessing that’s what you’re describing about the [0] element in print() .)

BTW, Vainaixr is using 5 as the slice stop because lists are ‘zero-indexed’, meaning that they start at zero. This is a little weird if you aren’t used to it, but is quite useful in general.

You picked a good exercise, Brad. Strings are a great place to start and with Python strings are a special case of lists. Perhaps you’ve already seen This tutorial page at docs.python.org that covers strings and lists in the first two sections.

Lists are one the many fun things to tinker with in Python. Once you get your example code working, try adding another colon and a negative [ : : step] value, like [ : : -1]. :slightly_smiling_face:

Thank you for explaining the reason for my error. It really helps me wrap my head around the logic behind the syntax. As I’m going through W3schools and my Udemy video course I’m trying to apply what I’m learning to an actual situation so I understand it better. I’m coming from a sales/customer service background for 25+ years so I’m taking it slow. :slight_smile:

1 Like