How to append ones to a list?

Question:

I have the following list –

 pts1_list = [
    [224.95256042, 321.64755249],
    [280.72879028, 296.15835571],
    [302.34194946, 364.82437134],
    [434.68283081, 402.86990356],
    [244.64321899, 308.50286865],
    [488.62979126, 216.26953125],
    [214.77470398, 430.75869751],
    [299.20846558, 312.07217407],
    [266.94125366, 119.36679077],
    [384.41549683, 442.05865479],
    [475.28448486, 254.28138733]]

I would like to append ones to this so that it finally looks like this –

 pts1_list = [
    [224.95256042, 321.64755249, 1],
    [280.72879028, 296.15835571, 1],
    [302.34194946, 364.82437134, 1],
    [434.68283081, 402.86990356, 1],
    [244.64321899, 308.50286865, 1],
    [488.62979126, 216.26953125, 1],
    [214.77470398, 430.75869751, 1],
    [299.20846558, 312.07217407, 1],
    [266.94125366, 119.36679077, 1],
    [384.41549683, 442.05865479, 1],
    [475.28448486, 254.28138733, 1]]

I have tried doing the following –

for i in range(len(pts1)):
    points1_list = [pts1[i]]
    points1_list = np.append(points1_list,1)
    
print(points1_list)
print(pts1_list)

for which print(points1_list) prints out only [475.28448486, 254.28138733, 1] i.e. the last element ; whereas if I print pts1_list, it prints out all the elements in the list. How do I get points1_list to also print out all the elements in the list, with a 1 appended to it? Thanks

Asked By: blazingcannon

||

Answers:

This can be solved using list addition. Out of the other answers, this is the most commonly used, easiest, and simplest. Read up on nested list comprehension.

points1_list = [i + [1] for i in pts1_list]
Answered By: Bituvo

Just loop through the matrix and append 1 to each list

for arr in pts1_list:
    arr.append(1)
    
print(pts1_list)
Answered By: Maxwell D. Dorliea

This seems like a strong use-case for Python’s map function. It basically runs a function for each element in an array and returns the resulting array. There are other ways to accomplish this, but this is probably one of the cleaner (and potentially faster, depending on Python backend stuff) methods. It is easy to see how this can be expanded out to similar methods

def append_one(row):
    return row.append(1)

pts1_list = map(append_one, pts1_list)

Further reading: https://www.geeksforgeeks.org/python-map-function/

Answered By: Zachary Brasseaux
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.