0

I want to create a classic card game in Python based on a users input. I want to ask them > players = int(input('How many players are playing? 2-4 '))

and depending if they say 2.

players = [[], []] will be created

but if they said 3

then players = [[], [], []] would be created

etc

so far all i can do is players [[], [], [], []] which means 4 players must always play the game??

4 Answers 4

1

You could do,

n = input("number: ")    # n = 2 say
out = [list() for i in range(n)] # [[], []]

See if it works for you.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use list comprehension:

players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]

Output:

>>> players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]
How many players are playing? 2-4 3
>>> players
[[], [], []]

Or you can use the * operator:

players = [[]] * int(input('How many players are playing? 2-4 '))

However, changing an element in the list when using second method would cause every sublist to change too. So for you the list comprehension method would be better.

E.g:

>>> players = [[]] * int(input('How many players are playing? 2-4 '))
How many players are playing? 2-4 3
>>> players
[[], [], []]
>>> players[1].append("hello")
>>> players
[['hello'], ['hello'], ['hello']]

Comments

1

You can do something like this

players = [ [] for x in range(int(input('How many players are playing? 2-4 ')))]

players = int(input('How many players are playing? 2-4 '))
players = [[]] * players

4 Comments

Well, now try to append something to the first sub-list.
you can do players[0].append("hello")
And then print the whole list. You'll be surprised :)
Additionally, I don't think it's a great idea to reuse the name players for both the input from the user (which is a number) and the container (which is a list). Try to use meaningful names, especially in dynamic languages.
0

Just say:

vectorPlayers = []

players = int(input("'How many players are playing? 2-4 '"))

for x in range(players):
    vectorPlayers.append([])


print(vectorPlayers)

This will create a vector with an empty vector in every position

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.