0

I want to make an array of filenames to loop through in python. In Perl I would write it like this:

my @array = qw (name00 .. name100)

or

foreach my $i (01..100)
{
     push(@array,$i);
}

Is there a similar way to do this in Python?

1 Answer 1

7

I'm not that familiar with Perl but if I understand the gist of what you are doing:

One-line list comprehension

>>> myArray = ['file' + str(i) for i in range(1,101)]
>>> myArray
['file1', 'file2', 'file3', 'file4', 'file5', 'file6', 'file7', 'file8', 'file9', 'file10', 'file11', 'file12', 'file13', 'file14', 'file15', 'file16', 'file17', 'file18', 'file19', 'file20', 'file21', 'file22', 'file23', 'file24', 'file25', 'file26', 'file27', 'file28', 'file29', 'file30', 'file31', 'file32', 'file33', 'file34', 'file35', 'file36', 'file37', 'file38', 'file39', 'file40', 'file41', 'file42', 'file43', 'file44', 'file45', 'file46', 'file47', 'file48', 'file49', 'file50', 'file51', 'file52', 'file53', 'file54', 'file55', 'file56', 'file57', 'file58', 'file59', 'file60', 'file61', 'file62', 'file63', 'file64', 'file65', 'file66', 'file67', 'file68', 'file69', 'file70', 'file71', 'file72', 'file73', 'file74', 'file75', 'file76', 'file77', 'file78', 'file79', 'file80', 'file81', 'file82', 'file83', 'file84', 'file85', 'file86', 'file87', 'file88', 'file89', 'file90', 'file91', 'file92', 'file93', 'file94', 'file95', 'file96', 'file97', 'file98', 'file99', 'file100']

For learning purposes, here is a more step-by-step way to do it in Python

myArray = []                     # initialize an empty array
for i in range(1,101):           # range produces a list [1,2,3, ... 99, 100]
    fileName = 'file' + str(i)   # converts i to string, then performs concatenation
    myArray.append(fileName)     # appends the concatenated string to the array
Sign up to request clarification or add additional context in comments.

2 Comments

I'd mention how to loop through it too.
Awesome. Thanks for showing me both ways Cyber. Exactly what I was looking for. Great answer!

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.