2

Suppose I have a list of tuples as follows:

listA = [ (B,2), (C,3), (D,4) ]

I would like to add another tuple (E,1) to this list. How can I do this?

And more specifically, I would like to add this tuple as the 1st tuple in the list so that I get:

newList = [ (E,1), (B,2), (C,3), (D,4) ]

I am using Python 2.7.

Thanks in advance!

Kyle Strand
  • 15,941
  • 8
  • 72
  • 167
activelearner
  • 7,055
  • 20
  • 53
  • 94

3 Answers3

4

If you are going to be appending to the beginning a collections.deque would be a more efficient structure:

from collections import deque

deq = deque([("B",2), ("C",3), ("D",4) ])

deq.appendleft(("E",1))

print(deq)
deque([('E', 1), ('B', 2), ('C', 3), ('D', 4)])

appending to the start of the deque is 0(1).

If you actually wanted a new list and to keep the old you can simply:

newList = [(E,1)] + listA 
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
3
listA.insert(index, item)

For you:

listA.insert(0, ('E', 1))

If you want it in your new variable, assign it AFTER inserting (thanks TigerHawk)

newList = listA

Important thing to remember, as well - as Padraic Cunningham pointed out - this has it so both lists are referencing the same object. If you change listA, you'll change newList. You can make a new object by doing some other things:

newList = listA[:]
newList = list(listA)
Matthew Runchey
  • 234
  • 2
  • 6
3

To add to beginning of this you just do

listA.insert(0, (E,1)).

Insert adds to a specific index of a list.

Read the docs: https://docs.python.org/2/tutorial/datastructures.html

DG1
  • 171
  • 1
  • 8