Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (19.9k points)

Given that:

l = [1,2,3,4,5]

What is the difference between l.pop(0) and l = l[1:] if we only consider final state of l?

It seems to me that contents of l should be the same, no matter which option I choose and simple tests seem to show the same, but I have a piece of code which behaves differently based on which operation I use.

I'm using Python 3.6.7 from Anaconda.

EDIT: Code example:

forward = range(10)

backward = forward[::-1]

parts = []

f_p = []

b_p = []

for f, b in zip(forward, backward):

    if len(f_p) == 3:

        parts.append((f_p, b_p))

        f_p = f_p[1:] # f_p.pop(0)

        b_p = b_p[1:] # b_p.pop(0)

    f_p.append(f)

    b_p.append(b)

print(parts)

Why are results different?

1 Answer

0 votes
by (25.1k points)

The major difference is that l.pop(0) will change the list and remove the first element from it, but, l[1:] will return a new list with all elements from list l except the first one. Slicing will not affect the original list.

Related questions

0 votes
1 answer
asked Jul 6, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 15, 2019 in Python by Sammy (47.6k points)
+2 votes
2 answers
asked May 23, 2019 in Python by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)

Browse Categories

...