Wednesday, May 20, 2020

Lists



Lists


There are 4 data types that represent collections of elements.


They are list, denoted by a pair of square braces []; tuple, which is denoted by a pair of parentheses (); set, which is denoted by a pair of {} with elements separated by commas; dictionary, which is represented by a set of {} with key-value pairs separated by a :.


   collection data type     Ordered   Changeable  IndexedDuplication allowed      
 list [,] YesYes Yes Yes
 tuple (,) Yes No Yes Yes
 set {,} No only subtract and add  No No
 dictionary {:} Yes Yes Yes No


The efficiency and security of your code can depend on the choice of your collection.

It turns out that the members of a list can have individual data member types mixed of, for example, a Boolean, string, or integers all in the same list ... it's valid.

mixedlist = [10, "apple", False]  # valid

Other special uses of the colon in list access
These behave in the same way as for strings.

mixedlist[0]   ===> 10
mixedlist[:2]  ===> 10 "apple"
mixedlist[:]    ===> 10, "apple", False
mixedlist[2:]  ===> "apple" False
mixedlist[-2:-1] ===> "apple"
mixedlist[-1] ===> False


Collections have a variety of methods available to them.


The insert() method will put in a string at a given index in the list. The insert method takes two arguments. If the index is -1, the new element will be inserted second from the right in the list.

# put "tree" at the left most position in mixedlist

mixedlist.insert(0, "tree") 
# results in mixedlist = ["tree", 10, "apple", False]

mixedlist.insert(-1, "tree") 
# results in mixedlist = [10, "apple", "tree", False]


The remove() method will take away an element from a list. If a list has duplicates it would only take away one element: the leftmost of those elements in the list.


mixedlist = [10, "apple", 10, "tree", False]

mixedlist.remove(10) # specify by item content, not index.
# results in mixedlist = ["apple",  10, "tree", False]


pop() will also remove an element from the list at a specified index. If you call pop without any index it removes the rightmost element only.

mixedlist = ["apple",  10, "tree", False]
mixedlist.pop(2) # indexing starts at 0
# results in mixedlist = ["apple",  10, False]

veggies = ["carrot", "lettuce", "radish"]
veggies.pop()
# results in veggies = ["carrot", "lettuce"]


del is a keyword, not a method available in Python but it does the same thing as the list pop method. In fact, if you del on a list without giving any index it will remove that variable entirely from memory.

cars = ["sedan", "SUV", "minivan"]
del cars
print(cars)
# results in an error: name 'cars' is not defined.

The clear() method will empty a list as opposed to fully eliminating it like del would; the list still exists although it'll be empty. 

cars = ["sedan", "SUV", "minivan"]
cars.clear() # takes no arguments
print(cars)
# no error
# results in []


Although one can make a true copy of a variable which represents a single element, for example,

 x = 10

(you can make a memory copy of x by saying)

 y = x. 

x and y are treated differently with different locations in memory.

That's not the same with the lists.

 w = ["a", "b"]

 followed by

 v = w

 does not create a new true copy; it instead creates a reference to w such that any changes to w will also be made right way in v because they share the same location in memory.

In order to create two separate list variables use the copy() method; you can also use the python list built-in constructor function. The python list function can also be considered as a constructor where you can use a double (( )) to create a list on the fly without actually making an explicit assignment using an equal sign.

states = ["Alabama", "Virginia", "Florida"]
doublestates = states.copy()
test = states is doublestates
print(test)
# returns False since the two are separate variables in memory.

# notice no use of [] but this is still a Python list
morestates = list(("Alabama", "Virginia", "Florida", "Maryland"))


There are three ways to join lists.

You can use a plus sign +, you can loop over the elements using for in or you can use the extend() method.


option 1
groceries = cars + veggies

# result is 
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']


option 2 # x is an ordered member of the veggies list
for x in veggies:
    cars.append(x)
    print(cars)

# result is
['sedan', 'SUV', 'minivan', 'carrot']
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce']
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']


option 3
cars = ["sedan", "SUV", "minivan"]
cars.extend(veggies)
print(cars)

# result is:
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']

the next option is not the same as the other three

option 4
cars = ["sedan", "SUV", "minivan"]
for x in veggies:
    cars.extend(x)
    print(cars)

# result 
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish', 'c', 'a', 'r', 'r', 'o', 't', 'l', 'e', 't', 't', 'u', 'c', 'e', 'r', 'a', 'd', 'i', 's', 'h']

The extend() method sees each character as a string of length 1 and operates accordingly.


Notice that in option 1 you must create a new variable groceries.

If you do not want to create a third variable but still want to use the +, use it as compound assignment operator

cars +=veggies
# cars gets appended by veggies
# the veggies variable does not change in this example


Check for existence of a value in a list:

veggies = ["carrot", "lettuce", "radish"]
if ('carrot') in veggies:
    print("yes")

# result is 
yes













No comments:

Post a Comment