• 0

[Python] How to make empty array?


Question

The geniuses at my uni decided to teach python instead of PHP, so now I'm stuck with it for my assignments. Anywho, how do you make an empty array in python? Everything I've searched up only tells you how to make them manually, hard coding all the items, not a single one tells you how to just make an empty array of x items. Anyone here know? Thx!

edit: nm got it

ary = []; #make list of 0 length
ary.append('whatever'); #add items

Edited by Primexx
Link to comment
https://www.neowin.net/forum/topic/627023-python-how-to-make-empty-array/
Share on other sites

5 answers to this question

Recommended Posts

  • 0
  Primexx said:
The geniuses at my uni decided to teach python instead of PHP, so now I'm stuck with it for my assignments. Anywho, how do you make an empty array in python? Everything I've searched up only tells you how to make them manually, hard coding all the items, not a single one tells you how to just make an empty array of x items. Anyone here know? Thx!

edit: nm got it

ary = []; #make list of 0 length
ary.append('whatever'); #add items

I am not a big python guy but I think I found it for you...

http://www.rexx.com/~dkuhlman/python_101/python_101.html

>>>

2.2.2 Sequences

2.2.2.1 What

There are several types of sequences in Python. We've already discussed strings. In this section we will describe lists and tuples. See http://www.python.org/doc/current/lib/typesseq.html for a description of the other sequence types (e.g. buffers and xrange objects).

Lists are dynamic arrays. They are arrays in the sense that you can index items in a list (for example "mylist[3]") and you can select sub-ranges (for example "mylist[2:4]"). They are dynamic in the sense that you can add and remove items after the list is created.

Tuples are light-weight lists, but differ from lists in that they are immutable. That is, once a tuple has been created, you cannot modify it. You can, of course, modify any (modifiable) objects that the tuple refers to.

Capabilities of lists:

Append items.

Insert items.

Add a list of items.

Capabilities of lists and tuples:

Index items.

Select a subsequence of items (also known as a slice).

Iterate over the items in the list or tuple.

2.2.2.2 When

Whenever you want to process a colletion of items.

Whenever you want to iterate over a collection of items.

Whenever you want to index into a collection of items.

2.2.2.3 How

To create a list use:

>>> items = [111, 222, 333]

>>> items

[111, 222, 333]

To add an item to the end of a list, use:

>>> items.append(444)

>>> items

[111, 222, 333, 444]

To insert an item into a list, use:

>>> items.insert(0, -1)

>>> items

[-1, 111, 222, 333, 444]

You can also push items onto the right end of a list and pop items off the right end of a list with append and pop.

>>> items.append(555)

>>> items

[-1, 111, 222, 333, 444, 555]

>>> items.pop()

555

>>> items

[-1, 111, 222, 333, 444]

And, you can iterate over the items in a list with the for statement:

>>> for item in items:

... print 'item:', item

...

item: -1

item: 111

item: 222

item: 333

item: 444

>>>

Sorry if that was no help :p

  • 0
  Primexx said:
The geniuses at my uni decided to teach python instead of PHP, so now I'm stuck with it for my assignments. Anywho, how do you make an empty array in python? Everything I've searched up only tells you how to make them manually, hard coding all the items, not a single one tells you how to just make an empty array of x items. Anyone here know? Thx!

edit: nm got it

ary = []; #make list of 0 length
 ary.append('whatever'); #add items

You definitely got it, though last I checked Python didn't use semicolons at the end (PHP habit?) :p

The same technique for arrays (known as lists in Python) can be used to create empty dictionaries (a.k.a. associative arrays, hash maps, etc.) or tuples:

lst = [] #empty list
dic = {} #empty dictionary
tup = () #empty tuple

Also, you can find the length using the len() function and the type using the type() function:

print type([]) #<type 'list'>
print type({}) #<type 'dict'>
print type(()) #<type 'tuple'>

#you can do the same with the len() function if you want
#  but I'm not going to

The idea is that you're calling the initializers/constructors for each object:

[] = list()

{} = dict()

() = tuple()

I'm no Python expert, but I know about those things. :p

It is really quite a nice language once you get used to it, but I can't say it is better or worse than PHP because I use both. There isn't anything better than PHP for websites, though I don't have anything against ASP/ASP.NET or CGI/Perl. Python is a great multi-purpose scripting language though - a nice replacement for the normal command line in Windows.

  • 0
  rpgfan said:
You definitely got it, though last I checked Python didn't use semicolons at the end (PHP habit?) :p

The same technique for arrays (known as lists in Python) can be used to create empty dictionaries (a.k.a. associative arrays, hash maps, etc.) or tuples:

lst = [] #empty list
dic = {} #empty dictionary
tup = () #empty tuple

Also, you can find the length using the len() function and the type using the type() function:

print type([]) #<type 'list'>
print type({}) #<type 'dict'>
print type(()) #<type 'tuple'>

#you can do the same with the len() function if you want
#  but I'm not going to

The idea is that you're calling the initializers/constructors for each object:

[] = list()

{} = dict()

() = tuple()

I'm no Python expert, but I know about those things. :p

It is really quite a nice language once you get used to it, but I can't say it is better or worse than PHP because I use both. There isn't anything better than PHP for websites, though I don't have anything against ASP/ASP.NET or CGI/Perl. Python is a great multi-purpose scripting language though - a nice replacement for the normal command line in Windows.

honestly, I hate python because of its lack of brackets (I also hate VB, etc for the same reason), lack of some functions (no switch or do-while?!), and majorly ****ed up syntax. And I had to guess-and-check to figure the list thing out, absolutely nowhere I searched ever said "Use var = []; to make an empty list, to which you could add stuff later".

oh, yea, the semicolons are from every single other language I use, so I tack them on (the interpreter doesn't complain about that, so it's all good) to read the code more comfortably...it just doesn't feel right without.

  • 0

You can use switch statements (sort of) via the combination of dictionaries and lambda functions. The idea that I found can be seen at http://simonwillison.net/2004/May/7/switch/ if you really want it, but I think if-elif-else statements work just as well. As one commenter mentioned, using it in combination with try-except blocks (and sometimes even a try-except-else-finally blocks) can help to create the "default:" part if necessary. Check out http://docs.python.org/ref/try.html for some more information on the way try-except-else-finally is used.

  • 0
  rpgfan said:
You can use switch statements (sort of) via the combination of dictionaries and lambda functions. The idea that I found can be seen at http://simonwillison.net/2004/May/7/switch/ if you really want it, but I think if-elif-else statements work just as well. As one commenter mentioned, using it in combination with try-except blocks (and sometimes even a try-except-else-finally blocks) can help to create the "default:" part if necessary. Check out http://docs.python.org/ref/try.html for some more information on the way try-except-else-finally is used.

yea I did use the dictionary + lambda for switch, I never thought of using a try-except for it though (never heard of finally, until now). seems like the dictionary is easier in any case.

if-else might work for a few options, but it gets really clumsy after you have tens of choices, and lambda has it's own drawbacks, so it's still lacking on python's part to not have something as basic as a switch. I just like the traditional syntax a lot more.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I have the Pixel 9 Pro XL...Unless this thing is "leaps and bounds" faster than the 9, I'll pass. And by leaps and bounds, I don't mean on benchmarks. "Real world" faster. Most people don't even come close to topping out the performance of their phones. Tensor G5 is Google's most powerful chip to date, boasting a staggering 36 percent performance leap over G4.
    • MIT's stunning 'bubble wrap' device squeezes water out from thin air even in deserts by Sayan Sen Image by Matteo Roman via Pexels Massachusetts Institute of Technology (MIT) engineers have built a new kind of device that can pull clean drinking water straight out of the air—no electricity needed. It’s designed for areas where water is scarce and traditional sources like rivers or lakes aren’t reliable. Right now, more than 2.2 billion people globally don’t have access to safe drinking water. In the United States alone, 46 million face water insecurity, with either no running water or water that’s not safe to drink. This new device, called an Atmospheric Water Harvesting Window (AWHW), uses a unique hydrogel panel that looks like black bubble wrap. These dome-shaped bubbles soak up water vapor from the air, especially at night when humidity is higher. During the day, sunlight makes the vapor inside evaporate. That vapor then condenses on a glass surface and drips down through a tube, turning into drinkable water. The AWHW doesn’t rely on power sources like batteries or solar panels. It’s completely passive, meaning it works on its own. The team tested a meter-sized panel in Death Valley, California, one of the driest places in North America, and got between 57.0 and 161.5 milliliters of water per day even with humidity as low as 21 percent. That’s more than what other similar passive devices have managed. “We have built a meter-scale device that we hope to deploy in resource-limited regions, where even a solar cell is not very accessible,” said Xuanhe Zhao, a professor at MIT. “It’s a test of feasibility in scaling up this water harvesting technology. Now people can build it even larger, or make it into parallel panels, to supply drinking water to people and achieve real impact.” Another cool part of the design is how they kept the water safe to drink. Usually, these kinds of hydrogels use salts like lithium chloride to absorb more vapor but that can lead to salt leaking into the water, which isn’t ideal. To solve this, MIT’s team mixed in glycerol, a compound that helps keep salt locked inside the gel. In testing, the lithium ion concentration in the harvested water stayed below 0.06 ppm (parts per million), which is way below the safe limit. The hydrogel domes also give the material more surface area, letting it collect more vapor. The outer glass panel is coated with a special polymer film that helps cool the glass, making it easier for vapor to condense. “This is just a proof-of-concept design, and there are a lot of things we can optimize,” said lead author Chang Liu, now a professor at the National University of Singapore. “For instance, we could have a multipanel design. And we’re working on a next generation of the material to further improve its intrinsic properties.” Published in Nature Water, the study says the AWHW could last at least a year and shows promise for making safe, sustainable water in places with harsh climates. The researchers believe an array of vertical panels could one day supply water to individual households, especially in remote or off-grid locations. Source: MIT News, Nature This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • Clear Linux is open source, indeed, so its source code is available for anyone. They're just shutting down its support from them, they're not forbidding anyone else from taking over.
    • Linux Mint is also my favorite distro, but I fear what will happen with it if Clem were to disappear tomorrow, to be honest.
    • Yeah, I totally get your point, which is possible it could happen. I just hope there is a few people around him who are similar to where if they took over things would run pretty much the same. if not, then yeah, it could start to decline rapidly etc. but I figure something that's been around for a longer period of time with a decent backing, and probably more users than most Linux distro's (which I would 'imagine' Mint is one of the more used Linux desktop distro's by volume of people who use it), is less likely to just disappear. but like you said, nothing is guaranteed. but I do think you are probably right in that Clem is probably the core of what keeps Mint, Mint. I like how it tends to stay pretty much the same with some slight tweaks here and there (but is largely the same) instead of that crap some people go for with change for the sake of change trying to create a overly fancy interface and other unnecessary stuff etc. I also feel Mint keeps a nice balance of things out-of-the-box where it's not too bloated, nor too striped down. p.s. but I see Mint as a better Ubuntu basically. but I get your point like if it was more of a really serious choice of needing a 'safe bet' to use long term, then yeah something like official Ubuntu would be one of the better choices for sure given what you said with it being backed by an actual company which makes it a safer bet than Mint which is smaller and 'could' potentially be more fragile.
  • Recent Achievements

    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
    • Dedicated
      MacDaddyAz earned a badge
      Dedicated
    • Explorer
      cekicen went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      506
    2. 2
      ATLien_0
      209
    3. 3
      Michael Scrip
      202
    4. 4
      Xenon
      146
    5. 5
      +FloatingFatMan
      121
  • Tell a friend

    Love Neowin? Tell a friend!