Some notes on lists in Java and Python

Java and Python both have collection types (or compound data types). For a general introduction into collection types, you might want to have a look at Wikipedia.

One of the most basic collection types is a list. In Java, you use the interface java.util.List to work with a list. This interface has several implementations like ArrayList and LinkedList, both in package java.util. The interface and implementations are part of the extensive collections framework. The Java Tutorial has a nice introduction into the collections framework.

You can create a list as follows.

List stringList = new ArrayList();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");

Note: before JDK 7, you had to use new ArrayList(). JDK 7 introduced the diamond operator .

The List interface provides all the functionality you would expect. You can ask for the length (or size), access elements by index, lookup elements, ask for a subset, iterate over the list or change elements by index.

System.out.println(stringList.size());

System.out.println(stringList.get(0));
System.out.println(stringList.get(2));

System.out.println(stringList.indexOf(“bar”));

List subList = stringList.subList(0, 2);

for (String s : subList) {
System.out.println(s);
}
subList.set(1, “baz”);

for (String s : subList) {
System.out.println(s);
}

In Python, lists are built into the language. You create a list using square brackets.

>>> mylist = ['spam', 'eggs', 'bacon']

The available operations are very similar to what you can do with java.util.List. Ask for the length, access elements by index, lookup elements, ask for a subset, iterate over the list or change elements by index.

>>> len(mylist)
3
>>> mylist[0]
'spam'
>>> mylist[2]
'bacon'
>>> mylist.index('eggs')
1
>>> sublist = mylist[0:2]
>>> for s in sublist:
...     print(s)
... 
spam
eggs
>>> sublist[1] = 'bacon'
>>> for s in sublist:
...     print(s)
... 
spam
bacon
>>>

Of course, there’s much more that can be done with lists. I suggest that you have a look at the Python documentation on data structures.

Advertisements
Some notes on lists in Java and Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s