0

I'm trying to append to a list in Python 3 but want to do this in the shortest amount of lines possible. In order to do this, I have created a blank 1D array and used basic iteration to append to it. I want to append the 2d array within the iteration as well as allowing the user to be able to input their data to the 2d arrays. I know the code below doesn't work. However, I wanted to know if this is possible to achieve?

I'd like the output to be like the following:

[First name, Second name], [First name, Second name], [First name, Second name]
Array = []

for i in range (0,4):
    Array.append([input("First name")][input("Second name")])

print(Array)
Georgy
  • 12,464
  • 7
  • 65
  • 73
Python3D
  • 3
  • 2
  • More general question for reference: [How to input matrix (2D list) in Python?](https://stackoverflow.com/questions/22741030/how-to-input-matrix-2d-list-in-python) – Georgy Jul 12 '19 at 10:16

2 Answers2

0

Your code seems wrong, it's unclear what you want to do. I'm assuming you want a list like :

[ ["Mark", "Wahlberg"], ["Matt", "Damon"] ]

you can do that like :

num_names = 5
name_arr = []

for i in range(num_names):
   temp_arr = list(input("Enter name space separated: ").split(" "))
   name_arr.append(temp_arr)

Enter your name like : "Matt Damon", it splits it into 2 strings and creates a list.

Raghav Kukreti
  • 552
  • 5
  • 18
0

Your question is a bit unclear. I understand that you want the output as:

[['Aaron', 'Armstrong'],['Barry', 'Batista'], ['Cindy', 'Wilson']]

And that you want least number of lines as possible, so this is how short I was able to make it using List Comprehension:

Array = [[input("First Name: "), input("Last Name: ")] for _ in range(4)]
print(Array)

Or make it one line with :

print([[input("First Name: "), input("Last Name: ")] for _ in range(4)])
syashakash
  • 16
  • 1
  • @Python3D If you are satisfied with the answer, consider accepting it. See [How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Georgy Jul 12 '19 at 10:25