Michael Swartz
Michael Swartz

Reputation: 858

Append two strings as a single element to a Python list

I want to append two strings as a single element to a Python list. This is a simplified example of my problem:

lowerCase = [['a', 'b', 'c', 'd', 'e']]
newList = []

# Append two pieces of data as a single element
i = 1;
for letter in lowerCase[0]:
    [newList.append(letter), newList.append(i)]
    i += 1

print newList
print len(newList)

What I get:

['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5]
10

What I want:

[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
5

Upvotes: 0

Views: 7881

Answers (3)

d4vsanchez
d4vsanchez

Reputation: 1994

The problem is in the for loop. It should be done this way:

for letter in lowerCase[0]:
    newList.append([letter, i])
    i += 1

Upvotes: 2

Blender
Blender

Reputation: 298196

Take a look at your current code:

[newList.append(letter), newList.append(i)]

This line creates a list out of the output of those two method calls. You don't actually use the list, so you're basically doing:

newList.append(letter)
newList.append(i)

You want to append both elements at once inside of one iterable:

newList.append([letter, i])  
newList.append((letter, i))  # Tuples are faster to create, as they're immutable

Also, you usually don't need to create and increment an i variable by hand. Just use enumerate:

newList = []

for index, letter in enumerate(lowerCase[0], start=1):
    newList.append((letter, index))

Or with a list comprehension:

newList = [(letter, index) for index, letter in enumerate(lowerCase[0], start=1)]

Upvotes: 0

Ayman
Ayman

Reputation: 11585

What you need is

newList.append([letter, i])

Upvotes: 2

Related Questions