Fin Harris
Fin Harris

Reputation: 45

Lists inside lists when reading from csv

This is my code:

names = []

filename = "names.csv"
filedir = ""
csv_file = os.path.join(filedir, filename)

with open(csv_file) as file:
    reader = csv.reader(file)
    for row in reader:
        name = row
        names.append(name)

print(names)

This is the output I am getting:

[['hello'], ['hello'], ['one'], ['two'], ['three']]

The output I want is:

['hello', 'hello', 'one', 'two', 'three']

I don't know why this is happening. If you can help, thanks in advance.

Upvotes: 0

Views: 45

Answers (5)

Felipe Netto
Felipe Netto

Reputation: 77

One line solution:

names = [['hello'], ['hello'], ['one'], ['two'], ['three']]

list(map(lambda x: x[0], names))

Upvotes: 0

Sapan Zaveri
Sapan Zaveri

Reputation: 518

A simplest way to do this:

for row in reader:
    [name] = row
    names.append(name)
print names

Upvotes: 0

PyPingu
PyPingu

Reputation: 1747

This is happening because csv.reader iterates through the rows as lists. It seems you only have a single element in each row of your csv?

If that is indeed the case, and is always the case, you can do two different things:

1)

with open(csv_file) as file:
    reader = csv.reader(file)
    for row in reader:
        name = row
        names.append(name[0])

2)

with open(csv_file) as file:
    reader = csv.reader(file)
    for row in reader:
        name = row
        names.extend(name)

Extend unpacks an iterable into the list.

Upvotes: 0

Khakhar Shyam
Khakhar Shyam

Reputation: 499

You can do this on names:

x=[['hello'], ['hello'], ['one'], ['two'], ['three']]
t = []
for i in x:
    for j in i:
     t.append(j)

or you can do the below in your case:

names = []
for row in reader:
    names.append(row[0])

Upvotes: 1

Gal Fridman
Gal Fridman

Reputation: 760

using default list:

new_names = [name for names_list in names for name in names_list]

using numpy:

import numpy as np
new_names = np.array(names).flatten()

Upvotes: 0

Related Questions