Pieter
Pieter

Reputation: 151

Add a number to the front of a number row python

In python there is the .append function to add a number to the back of a row:

coordinate_row.append(coordinate)

However, i would like to add a number to the front of a row. like this:

[1,2,3]

add 4

[4,1,2,3]

How can i do this?

Upvotes: 0

Views: 283

Answers (2)

Andrew
Andrew

Reputation: 3871

This will do the trick:

coordinate_row = [1, 2, 3]
coordinate = [4]
coordinate_row = coordinate + coordinate_row
print coordinate_row  # output:  [4, 1, 2, 3]

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118001

You can just use the + operator for this

>>> l = [1,2,3]
>>> l = [4] + l
>>> l
[4, 1, 2, 3]

Or in your case

coordinate_row = list(coordinate) + coordinate_row

As a function

def front_append(l, item):
    return [item] + l

>>> l = [1,2,3]
>>> l = front_append(l, 4)
>>> l
[4, 1, 2, 3]

Alternatively, you can use the list method insert with position 0

>>> l = [1,2,3]
>>> l.insert(0, 4)
>>> l
[4, 1, 2, 3]

Upvotes: 3

Related Questions