πŸ“• Node [[python lists and tuples]]
πŸ“„ Python Lists and Tuples.md by @KGBicheno

Python Lists and Tuples

Go to the[[Python Week 2 Main Page]] or the [[Python - Main Page]] Also see the [[Programming Main Page]] or the [[Main AI Page]]

For code examples see both the:

Tuples

Lists are also a sequential data type like tuples except that they are:

  • mutable, and
  • encapsulated by square brackets []

Because lists are mutable, functions can operate on the same list.

list1 = ["Breaking Benjamin", 10, 3]

list1.extend(["Rock", 11])

list1 now containts ["Breaking Benjamin", 10, 3, "Rock", 11]

!!! The difference between extend() and append()

Taake the previous example:

list1 = ["Breaking Benjamin", 10, 3]

list1.extend(["Rock", 11])

list1 now containts ["Breaking Benjamin", 10, 3, "Rock", 11]

==If we had instead used append(), the list would now only have one more element, a two-element list.==

list1 = ["Breaking Benjamin", 10, 3]

list1.append(["Rock", 11])

list1 now containts ["Breaking Benjamin", 10, 3, ["Rock", 11]]

Assigning and deleting elements

You can assign a new value to a list index by using the assignment operator =

list1[0] = "The Offspring"

list1 now containts ["The Offspring", 10, 3, ["Rock", 11]]

You can also use the del[] command to delete an element from the list by passing in the index.

del(list1[2])

list1 now containts ["The Offspring", 10, ["Rock", 11]]

Aliasing

When two variables reference the same object, changing the object through one variable changes it for the other variable too, sometimes without having intended to.

E.g.

list1 = ["Breaking Benjamin", 10, 3, "Rock", 11]
band_list = list1
# stuff happens in the program
list1[3] = "Christian Rock"
# more stuff happens, dev prints band_list, expecting original vals
print(band_list)
# is shocked to see they've become a christian rock band
# fin

Copying a list with some simple syntax

All you need to do to copy a list is use the following syntax

band_list = list1[:]

And boom, you have a copied list, no unexpected changes from aliasing.

Loading pushes...

Rendering context...