Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jason Chiu
4,373 PointsExtra Credit for Python Slice
Hi all,
How can I blend two different lists together using only the slice technique, as what was told to do in extra credit section of slicing?
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsOne solution is to walk down both lists and append each item to a results lists. The issue is how to handle the case where the two lists have different lengths. Using a simple index notation "[n]" will eventually raise an IndexError on the shorter list.
The nice feature of using slices is you are protected from indexing issues because the Alec returns an empty list of the index is it found.
For example:
# define s list
a =[1,2,3,4]
# get index 3 and 4
a[3] # 4
a[4] # raises error
# using slices
a[3:3] # [4]
a[4:4] # []
Using slices to crest a merge function:
def merge(a,b):
maxlen = max(len(a), len(b))
result = []
for idx in range(maxlen):
result.extend(a[idx:idx+1])
result.extend(b[idx:idx+1])
return result
a =[1,2,3,4]
b=['a', 'b', 'c', 'd', 'e', 'f']
print(merge(a,b))
# creates
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 'e', 'f']