Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lists(Slice method)

Tags:

python

I am a newbie to python,everywhere I read about list methods I see one thing

The slice method returns a "new" list

What is here meant by "new" list,and why is it faster then changing the original list?

Does it really matter if python manipulates the original list,I mean I cant use it anyway.

like image 694
Kartik Anand Avatar asked Jul 12 '26 23:07

Kartik Anand


1 Answers

With lists, you can do both:

1) create a new list (the original is left intact):

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

In [2]: l[:3]
Out[2]: [1, 2, 3]

In [3]: l
Out[3]: [1, 2, 3, 4, 5]

2) modify the list in-place:

In [6]: del l[3:]

In [7]: l
Out[7]: [1, 2, 3]

In [8]: l.append(15)

In [9]: l
Out[9]: [1, 2, 3, 15]

It's up to you to choose which way makes more sense for your problem.

In contrast to lists, tuples are immutable, which means that you can slice them, but you cannot modify them in place.

like image 66
NPE Avatar answered Jul 28 '26 18:07

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!