Python Forum
How can I produce a list of n times the same element?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I produce a list of n times the same element?
#1


I want to produce the list: ["*", "*", "*", "*", "*"].

Can this be done in a simple line? (I don't want to have to create a function to do it.)

So far I have been having to do the following, which is very inconvenient and tedious:

v = []
for i in xrange(5):
    v.append("*")
Reply
#2
 v = ('* '*5).split()
result:
Output:
>>> v ['*', '*', '*', '*', '*']
Reply
#3
(Nov-21-2017, 10:51 PM)Larz60+ Wrote:
 v = ('* '*5).split()
result:
Output:
>>> v ['*', '*', '*', '*', '*']

Thanks. How come it doesn't work to then append to v?
So for example:

v = ('* '*5).split()
print v.append("*")
gives an output of

Output:
None
Reply
#4
You code as list comprehensions.
>>> v = ['*' for i in range(5)]
>>> v
['*', '*', '*', '*', '*']
Or:
>>> v = ['*']  * 5
>>> v
['*', '*', '*', '*', '*']
Reply
#5
I can do it with the one i wrote:
>>> v = ('* '*5).split()
>>> v
['*', '*', '*', '*', '*']
>>> v.append('-')
>>> v
['*', '*', '*', '*', '*', '-']
>>>
Reply
#6
list.append() will append the item, but it returns None.  Since you're print()ing the return value of list.append(), that's why you see None.
Reply
#7
v = ["*"] * 5
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Produce One file Per PurchaseOrder jland47 1 293 Jan-26-2024, 11:38 AM
Last Post: Larz60+
  list in dicitonary element problem jacksfrustration 3 626 Oct-14-2023, 03:37 PM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 1,157 Nov-15-2022, 08:40 PM
Last Post: tester_V
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,738 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,162 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  How to find the second lowest element in the list? Anonymous 3 1,908 May-31-2022, 01:58 PM
Last Post: Larz60+
  check if element is in a list in a dictionary value ambrozote 4 1,885 May-11-2022, 06:05 PM
Last Post: deanhystad
  Using multiprocessing to produce objects for i in range lucasrohr 6 1,583 Feb-02-2022, 03:53 PM
Last Post: lucasrohr
  sorting a list of lists by an element leapcfm 3 1,807 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Convert each element of a list to a string for processing tester_V 6 5,174 Jun-16-2021, 02:11 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020