[source code] Python Programming Tutorial - 5 - Lists

+2 Bucky Roberts · August 26, 2014

>>> players = [29, 58, 66, 71, 87]
>>> players[2]
66
>>> players[2] = 68
>>> players
[29, 58, 68, 71, 87]
>>> players + [90, 91, 98]
[29, 58, 68, 71, 87, 90, 91, 98]
>>> players
[29, 58, 68, 71, 87]
>>> players.append(120)
>>> players
[29, 58, 68, 71, 87, 120]
>>> players[:2]
[29, 58]
>>> players[:2] = [0, 0]
>>> players
[0, 0, 68, 71, 87, 120]
>>> players[:2] = []
>>> players
[68, 71, 87, 120]
>>> players[:] = []
>>> players
[]

Post a Reply

Replies

Oldest  Newest  Rating
0 Gary Murphy · August 27, 2014
Hey Bucky
At the end of the video you showed how to clear a list by writing

players[:] = []


is the [:] necessary?  Will you get the same results by writing

players = []


Could you explain the difference if there is one?

By the way, I am using Python 2.7.8 instead of Python 3.x as part of a course I'm doing.  Apparently it has more libraries available to it at the moment.
I realize there are some differences and this could be one of them.

Thanks!
0 Bucky Roberts · August 27, 2014
There are no differences when printing them out. Both of these lines will print the exact same thing. 
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters)
print(letters[:])

It's common practice to only use [:] when making slices. 
0 Gary Murphy · August 27, 2014
Ok, cool.  Then I assume the same applies to assigning different values or clearing a list.
Thanks for that.
0 Anirudh Kumar · September 15, 2016
Hey Bucky I recently started watching your python tutorials and I have a doubt
Can we have a string argument in list of integers?
Lke,for example:
variable=[12,23,,34,45,"string"]
Is this valid??
0 Olivier Hassaoui St-Amour · November 29, 2016
Is your favorite team the Pittsburgh Penguins?
players [ Fleury, Letang, Lemieux, Malkin, Crosby ]
Lemieux trade for Jagr (bad trade tho)
  • 1

Python

107,241 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator